【发布时间】: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"
}
]
}
]
}
如果我尝试在使用 PrototypeJS 或 json2.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 的同一对象。
谁能详细说明发生了什么以及为什么会有这种差异?
我错过了什么?
【问题讨论】:
-
看起来这可能是一个错误,将 Fiddle 更改为使用 Prototype 1.7.1 似乎会产生预期的结果。看到这个:github.com/bestiejs/json3/issues/8
-
看起来它只是对整个
groups数组进行了 JSON 编码。 -
重复? stackoverflow.com/questions/710586/json-stringify-bizarreness ...从那个问题的答案中,
delete Array.prototype.toJSON -
是的,绝对是骗子。谢谢@crazy-train
标签: javascript json