Javascript 如何json_encode php数组但没有引号的键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13523729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to json_encode php array but the keys without quotes
提问by Danny
I'm trying to plot (with Flot) a pie chart with some data
我正在尝试用一些数据绘制(使用Flot)饼图
var data = <?php echo json_encode($data)?>
The result I get from that is this:
我从中得到的结果是这样的:
var data = [
{"label":"Crear Usuario", "data":"2"},
{"label":"Impresoras", "data":"1"},
{"label":"Problema Correo", "data":"1"},
{"label":"Requisicion Equipo", "data":"1"},
{"label":"Sitio Web", "data":"1"}
]
The problem here is that I need the labeland datawithout the quotes, I already tried json_encode($data, JSON_NUMERIC_CHECK);but only removes the quotes from the numbers.
这里的问题是我需要label和data没有引号,我已经尝试过json_encode($data, JSON_NUMERIC_CHECK);但只从数字中删除了引号。
The following format is what I need:
以下格式是我需要的:
var data = [
{label:"Crear Usuario",data:2}, ...
采纳答案by aleation
First, you have to generate your array in php so the data's value are integers, not strings:
首先,您必须在 php 中生成数组,以便数据的值是整数,而不是字符串:
I emulated your array from your json_encode(), I guess it looks like this (or it should):
我从你的 json_encode() 模拟了你的数组,我想它看起来像这样(或者应该):
$array = array(
array("label" => "Crear Usuario", "data" => 2),
array("label" => "Impresoras", "data" => 1),
array("label" => "Problema Correo", "data" => 1),
array("label" => "Requisicion Equipo", "data" => 1),
array("label" => "Sitio Web", "data" => 1)
);
$data = json_encode($array);
- Notice that the 2 and 1's are unquoted, so this way they are integers, this is important.
- 请注意,2 和 1 未加引号,因此它们是整数,这很重要。
Then you are missin in Javascript the JSON.parse() to actually make that output into a json object:
然后你在 Javascript 中缺少 JSON.parse() 来实际将该输出转换为一个 json 对象:
<script>
var data = '<?php echo $data; ?>';
var json = JSON.parse(data);
console.log(json);
console.log(json[0]);
</script>
- Notice that var data = ... is SINGLE QUOTED, so you catch the echo from php as a String
- 请注意 var data = ... 是单引号,因此您可以将来自 php 的回显作为字符串
The console.log()'s output this for me:
console.log() 为我输出这个:
[Object, Object, Object, Object, Object] // First console.log(): one object with the 5 Objects.
Object {label: "Crear Usuario", data: 2} // secons console log (json[0]) with the first object
Looks like what you need, am I right?
看起来像你需要的,对吗?
回答by DNS
There's no difference between quoted and unquoted keys. The problem is with the quoting around the actual data values, since Flot requires numbers, not strings.
带引号和不带引号的键之间没有区别。问题在于实际数据值周围的引用,因为 Flot 需要数字,而不是字符串。
The json_encode function decides to whether to quote based on the type of data you're giving it. In this case it looks like whatever operations you're performing to create $data are producing string values instead of integers. You need to re-examine those operations, or explicitly tell PHP to interpret them as numbers, using (int) or (float) casting, or the intval/floatval functions.
json_encode 函数根据您提供的数据类型决定是否引用。在这种情况下,看起来您为创建 $data 执行的任何操作都在生成字符串值而不是整数。您需要重新检查这些操作,或者明确地告诉 PHP 将它们解释为数字,使用 (int) 或 (float) 转换,或 intval/floatval 函数。
回答by Marcin Orlowski
Try something like this:
尝试这样的事情:
function buildBrokenJson( array $data ) {
$result = '{';
$separator = '';
foreach( $data as $key=>$val ) {
$result .= $separator . $key . ':';
if( is_int( $val ) ) {
$result .= $val;
} elseif( is_string( $val ) ) {
$result .= '"' . str_replace( '"', '\"', $val) . '"';
} elseif( is_bool( $val ) ) {
$result .= $val ? 'true' : 'false';
} else {
$result .= $val;
}
$separator = ', ';
}
$result .= '}';
return $result;
}
and when run
当运行时
$a = array("string"=>'Crear "Usuario', 'foo'=>':', "int"=>2, "bool"=>false);
var_dump( buildBrokenJson($a) );
it gives:
它给:
string(54) "{string:"Crear \"Usuario", foo:":", int:2, bool:false}"
回答by Ekene Madunagu
I created a class to format json with php without quotes on the keys here is it
我创建了一个类来用 php 格式化 json,这里的键上没有引号
class JsonFormatter
{
static $result = '';
static $separator = '';
public static function iterateArray($data) : string
{
static::$result .= '[';
static::$separator = '';
foreach ($data as $key => $val) {
if (is_int($val)) {
} elseif (is_string($val)) {
static::$result .= '"' . str_replace('"', '\"', $val) . '"';
} elseif (is_bool($val)) {
static::$result .= $val ? 'true' : 'false';
} elseif (is_object($val)) {
static::iterateObject($val);
static::$result .= ', ';
} elseif (is_array($val)) {
static::iterateArray($val);
static::$result .= ', ';
} else {
static::$result .= $val;
}
if (!is_int($val)) {
static::$separator = ', ';
}
}
static::$result .= ']';
return static::$result;
}
public static function iterate($data)
{
if (is_array($data)) {
static::iterateArray($data);
} elseif (is_object($data)) {
static::iterateObject($data);
}
return static::$result;
}
public static function iterateObject($data)
{
static::$result .= '{';
static::$separator = '';
foreach ($data as $key => $val) {
static::$result .= static::$separator . $key . ':';
if (is_int($val)) {
static::$result .= $val;
} elseif (is_string($val)) {
static::$result .= '"' . str_replace('"', '\"', $val) . '"';
} elseif (is_bool($val)) {
static::$result .= $val ? 'true' : 'false';
} elseif (is_object($val)) {
static::iterate($val, true);
static::$result .= ', ';
} elseif (is_array($val)) {
static::iterateArray($val, true);
static::$result .= ', ';
} else {
static::$result .= $val;
}
static::$separator = ', ';
}
static::$result .= '}';
return static::$result;
}
}
you can now call
你现在可以打电话
$jsonWithoutKeyQuotes = JsonFormatter::iterate($data);
thanks to Marcin Orlowski
感谢 Marcin Orlowski
回答by Brian Layman
TL;DR: Missing quotes is how Chrome shows it is a JSON object instead of a string. Ensure that you have Header('Content-Type: application/json; charset=UTF8'); in PHP's AJAX response to solve the real problem.
TL;DR:缺少引号是 Chrome 显示它是 JSON 对象而不是字符串的方式。确保您有 Header('Content-Type: application/json; charset=UTF8'); 在 PHP 的 AJAX 响应中解决了真正的问题。
DETAILS: A common reason for wanting to solve this problem is due to finding this difference while debugging the processing of returned AJAX data.
细节:想要解决这个问题的一个常见原因是因为在调试返回的 AJAX 数据的处理时发现了这个差异。
In my case I saw the difference using Chrome's debugging tools. When connected to the legacy system, upon success, Chrome showed that there were no quotes shown around keys in the response according to the debugger. This allowed the object to be immediately treated as an object without using a JSON.parse() call. Debugging my new AJAX destination, there were quotes shown in the response and variable was a string and not an object.
I finally realized the true issue when I tested the AJAX response externally saw the legacy system actually DID have quotes around the keys. This was not what the Chrome dev tools showed.
The only difference was that on the legacy system there was a header specifying the content type. I added this to the new (WordPress) system and the calls were now fully compatible with the original script and the success function could handle the response as an object without any parsing required. Now I can switch between the legacy and new system without any changes except the destination URL.
就我而言,我使用 Chrome 的调试工具看到了不同之处。当连接到旧系统时,成功后,Chrome 显示根据调试器,响应中的键周围没有显示引号。这允许在不使用 JSON.parse() 调用的情况下立即将对象视为对象。调试我的新 AJAX 目标时,响应中显示了引号,并且变量是字符串而不是对象。
当我在外部测试 AJAX 响应时,我终于意识到了真正的问题,看到遗留系统实际上在键周围有引号。这不是 Chrome 开发工具显示的内容。唯一的区别是在遗留系统上有一个指定内容类型的标头。我将它添加到新的 (WordPress) 系统中,现在调用与原始脚本完全兼容,并且成功函数可以将响应作为对象处理,无需任何解析。现在我可以在旧系统和新系统之间切换,除了目标 URL 之外没有任何更改。

