【问题标题】:Noticing an odd difference between different implementations of JSON.stringify注意到 JSON.stringify 的不同实现之间的奇怪差异
【发布时间】:2013-07-12 15:45:12
【问题描述】:

假设我有一个像这样相当嵌套的 JS 对象,我需要对其进行 JSON 编码:

var foo = { 
    "totA": -1,
    "totB": -1,
    "totC": "13,052.00",
    "totHours": 154,
    "groups": [
        {"id": 1,
        "name": "Name A",
        "billingCodes": [
            {"bc": "25", "type": "hours", "hours": "5", "amount": "$25.00"}
        ]}
    ] 
};

如果我使用原生浏览器 JSON.stringify 对其进行 JSON 编码(在 Chrome、Firefox、IE9/10 中测试),我会得到一个如下所示的 JSON 字符串(这是我所期望的):

Native JSON.stringify JSFiddle example

{
    "totA": -1,
    "totB": -1,
    "totC": "13,052.00",
    "totHours": 154,
    "groups": [
        {
            "id": 1,
            "name": "Name A",
            "billingCodes": [
                {
                    "bc": "25",
                    "type": "hours",
                    "hours": "5",
                    "amount": "$25.00"
                }
            ]
        }
    ]
}

如果我尝试在使用 PrototypeJSjson2.js 的页面上做同样的事情,就会出现奇怪的现象。

在这种情况下,same 对象上的JSON.stringify 会返回以下 JSON:

ProtypeJS JSON.stringify JSFiddle example

{
    "totA": -1,
    "totB": -1,
    "totC": "13,052.00",
    "totHours": 154,
    "groups": "[{\"id\": 1, \"name\": \"Name A\", \"billingCodes\": [{\"bc\": \"25\", \"type\": \"hours\", \"hours\": \"5\", \"amount\": \"$25.00\"}]}]"
}

显然,上面的问题是一个问题,因为它没有将 JSON 解码为最初传递给 JSON.stringify 的同一对象。

谁能详细说明发生了什么以及为什么会有这种差异?

我错过了什么?

【问题讨论】:

标签: javascript json


【解决方案1】:

这是因为原生 JSON.stringify 尊重 toJSON 方法,而 Prototype 将这些添加到所有地方。不幸的是,native 和 Prototype 似乎以不同的方式理解 toJSON:虽然 native 期望它返回一个用作文字值的 string,但 Prototype 的 toJSON 返回已经格式化的 JSON 块应按原样使用。因此存在差异。

这很好用:

delete Array.prototype.toJSON;
document.getElementById('out').innerHTML += JSON.stringify(foo);

http://jsfiddle.net/Ky3tv/2/

此外,这似乎已在 Prototype 1.7 中得到修复。我猜他们现在在添加 toJSON 方法之前检查原生 JSON。

【讨论】:

  • 我想他是在问为什么会有不同。
猜你喜欢
  • 2020-02-21
  • 1970-01-01
  • 2011-04-21
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 2012-05-11
  • 2021-10-05
  • 1970-01-01
相关资源
最近更新 更多