是否有可能json_encode在PHP中未定义的值?

chi*_*NUT 2 javascript php json undefined morris.js

我正在尝试json编码变量以具有值undefined,如javascript关键字undefined.我试图谷歌这个,但显示的唯一结果是人们在他们的PHP脚本中得到错误,实际的功能json_encode是未定义的.有办法做undefined吗?要对值进行编码,NULL它只是null没有引号."undefined"在php中使用它将它视为一个字符串,当然undefined不起作用,因为php认为这是一个常量.

我在javascript中试过这个:

JSON.stringify([undefined,null]);
Run Code Online (Sandbox Code Playgroud)

但它回来了

[null,null]
Run Code Online (Sandbox Code Playgroud)

那么甚至可以对值进行编码undefined吗?

我问的原因是我正在使用morris.js图表​​库,当你的折线图缺少数据点时,它处理的null值与值不同undefined,我希望它们被处理为undefined.我意识到我可以通过我的JSON对象循环并将所有nulls 转换为undefineds,但我想知道它是否甚至可以编码undefined.

一般来说,有几种情况undefined可能会有不同的处理方式,null因此适用于所有这些情况.

谢谢!

Jac*_*din 6

不,JSON不支持值undefined.最亲近的亲戚是nullfalse.根据本说明书中,有效的JSON值包括:字符串,数字,对象,数组true,falsenull.

而且,你如何检查它在物体中的存在?1

var a = {"key1":undefined,"key2":"value2"};
var b = {"key2":"value2"};
if(typeof(a.key1) == typeof(b.key1)){
    alert('absent in both!');
}
Run Code Online (Sandbox Code Playgroud)

我的小提琴.

如果您希望未定义属性,请将其删除,例如在PHP unset之前使用json_encode:

$a = array('key1' => null, 'key2' => 'value2');
unset($a['key1']);
json_encode($a); // {"key2":"value2"}
Run Code Online (Sandbox Code Playgroud)

1您可以使用for ... in循环.