我正在尝试对变量进行 json 编码,使其具有 undefined
的值,如 javascript 关键字 undefined
中所示。我试着用谷歌搜索这个,但唯一出现的结果是人们在他们的 php 脚本中遇到错误,实际函数 json_encode
未定义。有没有办法做未定义的?要对值 NULL
进行编码,它只是不带引号的 null
。在 php 中使用 "undefined"
将其视为字符串,当然 undefined
不起作用,因为 php 认为这是一个常量。
我在 javascript 中试过这个:
JSON.stringify([undefined,null]);
但它回来了
[null,null]
那么是否有可能对值undefined
进行编码?
我问的原因是我正在使用 morris.js 图表库,当您的折线图缺少数据时,它处理 null
值的方式不同于 undefined
值点,我希望将它们作为 undefined
处理。我意识到我可以遍历我的 JSON
对象并将所有 null
转换为 undefined
,但我想知道是否有可能编码 undefined
.
一般来说,在某些情况下,undefined
的处理方式可能与 null
不同,因此这适用于所有情况。
谢谢!
最佳答案
没有。 JSON 不支持 undefined
值。最近的亲戚是 null
或 false
。根据the specification ,有效的 JSON 值为:字符串、数字、对象、数组、true
、false
和 null
。
此外,您将如何检查它是否存在于对象中?1
var a = {"key1":undefined,"key2":"value2"};
var b = {"key2":"value2"};
if(typeof(a.key1) == typeof(b.key1)){
alert('absent in both!');
}
参见 my fiddle .
如果您希望某个属性未定义,请将其删除,例如在 PHP 中使用 unset
在 json_encode
之前:
$a = array('key1' => null, 'key2' => 'value2');
unset($a['key1']);
json_encode($a); // {"key2":"value2"}
1 您可以使用 for...in循环。
关于javascript - 是否可以对php中未定义的值进行json_encode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21420006/