【问题标题】:Can I get JSON.stringify to include keys with value undefined? [duplicate]我可以让 JSON.stringify 包含值未定义的键吗? [复制]
【发布时间】:2026-02-07 18:45:02
【问题描述】:

我使用看起来像这样的对象(来跟踪一些事情):

myObj = {
        key1: undefined,
        key2: undefined,
    }
     
console.log(JSON.stringify(myObj));
console.log(Object.entries(myObj))

令我惊讶的是,我刚刚注意到JSON.stringify(myObj) 只给出了{}

查看 MDN,replacer 参数的描述说 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify):

如果此值为 null 或未提供,则对象的所有属性 包含在生成的 JSON 字符串中。

这似乎是错误的。

我是否必须为 replacer 参数编写一个函数,或者? (这是 Chrome 中的错误吗?还是 MDN 上的信息有误?)

【问题讨论】:

  • 什么replacer 参数?该对象为空,因为它没有定义的属性。不确定这与替换器有什么关系?
  • 使用 null 而不是 undefined
  • I already have...。你能解释一下这与替换器有什么关系吗?
  • 不在(有效)JSON 中:A JSON value can be an object, array, number, string, true, false, or null.
  • 这是你的替代品:var string = JSON.stringify( obj, function(k, v) { return v === undefined ? null : v; } );

标签: javascript json google-chrome


【解决方案1】:

“未定义”不是有效的 json 值,即使它在 javascript 中有效。来自official json standard(ECMA-404,第 5 节) 对于 JSON,请使用 null 而不是 undefined

console.log(JSON.stringify(myObj = {
    key1: null,
    key2: null,
}));

【讨论】:

  • 我已经在评论中回答了这个问题
  • 谢谢,我明白了。这解释了JSON.stringify 的行为。但这有点令人困惑。
  • @mplungjan 对不起,我误解了你的评论。 (我以为是关于 JSON.stringify 的论点。)
  • null 和 JavaScript 引擎的这种使用有什么想法吗?
最近更新 更多