【问题标题】:Difference between json.js and json2.jsjson.js 和 json2.js 的区别
【发布时间】:2009-02-16 03:15:35
【问题描述】:

谁能告诉我这两个 JSON 解析器有什么区别?

https://github.com/douglascrockford/JSON-js/blob/master/json.js
https://github.com/douglascrockford/JSON-js/blob/master/json2.js

我有一个 2007 年 4 月 13 日的 JSON 文件(它有 parseJSON 等方法)。我在任何新版本中都没有看到这些方法。

【问题讨论】:

  • 你可以在这里找到新文件github.com/douglascrockford/JSON-js
  • 对于遇到这个问题的人想知道这些文件是什么,请知道没有理由在现代浏览器中使用它们。来自GitHub repo:“在当前的浏览器上,[json2.js] 什么都不做,更喜欢内置的 JSON 对象。没有理由使用这个文件,除非命运强迫你支持 IE8,这是没有人应该做的事情必须再做一次。”

标签: json


【解决方案1】:

来自他们的代码:

// Augment the basic prototypes if they have not already been augmented.
// These forms are obsolete. It is recommended that JSON.stringify and
// JSON.parse be used instead.

if (!Object.prototype.toJSONString) {
    Object.prototype.toJSONString = function (filter) {
        return JSON.stringify(this, filter);
    };
    Object.prototype.parseJSON = function (filter) {
        return JSON.parse(this, filter);
    };
}

我猜 parseJSON 已经过时了,因此新版本 (json2) 甚至不再使用它了。但是,如果您的代码经常使用parseJSON,您可以在某处添加这段代码以使其再次工作:

    Object.prototype.parseJSON = function (filter) {
        return JSON.parse(this, filter);
    };

【讨论】:

  • 谢谢,看来 parseJSON 已经被 JSON.parse 取代了?另外,toJSONString 呢?我们现有的代码使用了很多这样的方法: boolean.toJSONString() date.toJSONString() number.toJSONString() object.toJSONString() string.toJSONString()
  • 然后还添加第一段代码,你指定的所有值都是对象,因此它们都会自动转换为使用 JSON.stringify。
  • 谢谢!我会试试这个。那么,我可以将这些函数添加到 json.js 文件中吗?
  • "absolete" - 绝对的还是过时的?
  • "absolete" - 当它绝对过时时。
【解决方案2】:

引用here:

“JSON2.js - 去年年底,Crockford 悄悄发布了他的 JSON API 的新版本,取代了他现有的 API。重要的区别在于它使用了单个基础对象。”

【讨论】:

    【解决方案3】:

    我还注意到 json2 字符串化数组与 json2007 不同。

    在 json2007 中:

    var array = [];
    array[1] = "apple";
    array[2] = "orange";
    alert(array.toJSONString()); // Output: ["apple", "orange"].
    

    在json2中:

    var array = [];
    array[1] = "apple";
    array[2] = "orange";
    alert(JSON.stringify(array)); // Output: [null, "apple", "orange"].
    

    【讨论】:

    • json2 在这种情况下是正确的。 json2007 忽略索引 0 处的第一个元素是错误的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    • 1970-01-01
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多