javascript - 为什么 JSON.stringify 会忽略值未定义的键?

标签 javascript json

更准确地说,我理解为什么这在技术上会发生 - 因为 undefined 不是有效的 JSON 类型:

var breakfast = {
    "cereal" : "fruit loops",
    "pastry" : undefined
};

console.log(breakfast);
// -> { cereal: 'fruit loops', pastry: undefined }

console.log(JSON.stringify(breakfast));
// -> {"cereal":"fruit loops"}

我的问题是 - 为什么这被认为是可接受的行为?我想将 undefined 作为 API 或其他内容的一部分进行传递,这显然是有正当理由的。这似乎有些危险——为什么函数不引发错误,而是厚颜无耻地自行更改我的数据而不发出警告?这看起来有点像 JS 的运行线程。

最佳答案

这个问题的答案在于 ECMA-262 spec .在 24.3.2 JSON.stringify ( value [ , replacer [ , space ] ] ) 部分,规范明确指出:

NOTE 2

The undefined value is not rendered.

进一步:

NOTE 5

Values that do not have a JSON representation (such as undefined and functions) do not produce a String. Instead they produce the undefined value. In arrays these values are represented as the String null. In objects an unrepresentable value causes the property to be excluded from stringification.

因此,您使用的 JSON.stringify() 完全遵循现有的 ECMA 规范。

即使使用替换器,没有特别指定您自己的函数,默认替换器规则声明items 应该只被附加:

24.3.2 Subsection 4.b.5.g

If item is not undefined and item is not currently an element of PropertyList

关于javascript - 为什么 JSON.stringify 会忽略值未定义的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31284216/

相关文章:

javascript - React 钩子(Hook)在事件处理程序中不起作用

javascript - 在 Safari 中为复杂对象调用 JSON.stringify 错误

xml - 为什么在 Google API 文档中通常建议使用 JSON 而不是 XML?

javascript - json 和 Utc 日期时间

javascript - Laravel - 修改 API 数据只是为了方便

javascript - 当视口(viewport)狭窄时打开下拉菜单时 Bootstrap 导航栏无法正确调整大小

javascript - 如何获取 <img> 标签的 HTTP 状态码

javascript - IE8 - "object doesn' t 在缩小的返回语句上支持此属性或方法

json - 使用 Terraform 创建 Azure 策略

javascript - 如何在vuex的actions.js中使用router?