JSON.stringify() 数组与 Prototype.js 的奇怪之处

问题描述:

我试图找出我的 json 序列化出了什么问题,将我的应用程序的当前版本与旧版本一起使用,并且我发现 JSON.stringify() 的工作方式存在一些令人惊讶的差异(使用来自的 JSON 库)json.org).

I'm trying to figure out what's gone wrong with my json serializing, have the current version of my app with and old one and am finding some surprising differences in the way JSON.stringify() works (Using the JSON library from json.org).

在我的旧版应用中:

 JSON.stringify({"a":[1,2]})

给我这个;

"{"a":[1,2]}"

在新版本中,

 JSON.stringify({"a":[1,2]})

给我这个;

"{"a":"[1, 2]"}"

知道什么可以改变使同一个库在新版本中在数组括号周围加上引号吗?

any idea what could have changed to make the same library put quotes around the array brackets in the new version?

由于 JSON.stringify 最近在一些浏览器中发布,我建议使用它而不是 Prototype 的 toJSON.然后,您将检查 window.JSON &&window.JSON.stringify 并且仅包含 json.org 库,否则(通过 document.createElement('script')...).要解决不兼容问题,请使用:

Since JSON.stringify has been shipping with some browsers lately, I would suggest using it instead of Prototype’s toJSON. You would then check for window.JSON && window.JSON.stringify and only include the json.org library otherwise (via document.createElement('script')…). To resolve the incompatibilities, use:

if(window.Prototype) {
    delete Object.prototype.toJSON;
    delete Array.prototype.toJSON;
    delete Hash.prototype.toJSON;
    delete String.prototype.toJSON;
}