Javascript IE 8 支持 JSON.stringify() 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3326893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:10:18  来源:igfitidea点击:

Is JSON.stringify() supported by IE 8?

javascript

提问by user246114

I need to use:

我需要使用:

JSON.stringify()

which should be supported by Chrome, Safari, and Firefox. I think IE8 also has support for the JSON object. I think IE7 and 6 do not, so I'm doing this:

Chrome、Safari 和 Firefox 应该支持它。我认为 IE8 也支持 JSON 对象。我认为 IE7 和 6 没有,所以我这样做:

<!--[if lt IE 8]>
    <script src="http://www.json.org/json2.js"></script>
<![endif]-->

so, I think this will import the external JavaScript only if IE6 & 7. I looked at the URL where the script is hosted, they are including only if the IE version is less than 9:

所以,我认为这只会在 IE6 和 7 时导入外部 JavaScript。我查看了托管脚本的 URL,它们仅在 IE 版本小于 9 时才包含:

http://code.google.com/p/html5shiv/
<!--[if lt IE 9]>
    <script src="http://www.json.org/json2.js"></script>
<![endif]-->

so should I be including this for IE 8 too?

所以我也应该为 IE 8 包含这个吗?

回答by whitneyland

To answer the question in the title directly, yes IE8 supports JSON.stringify()natively.

直接回答标题中的问题,是IE8原生支持的JSON.stringify()

IE8 is the first version of IE to get this support, and the functionality is explained in detail by the dev team here: http://blogs.msdn.com/b/ie/archive/2008/09/10/native-json-in-ie8.aspx

IE8 是第一个获得此支持的 IE 版本,开发团队在此处详细解释了该功能:http: //blogs.msdn.com/b/ie/archive/2008/09/10/native-json -in-ie8.aspx

The answer the second part of the question, yes you would need to include alternate functionality for IE6/IE7. Something like Modernizr can make it easy to check this.

回答问题的第二部分,是的,您需要为 IE6/IE7 包含替代功能。像 Modernizr 这样的东西可以很容易地检查这个。

Also note if the user is in Compatibility View in IE8, the JSON object will not be available.

另请注意,如果用户处于 IE8 的兼容性视图中,则 JSON 对象将不可用。

回答by ggc

If you try JSON.stringify()using IE 8 you need to ensure it is not working in compatibility mode. See JSON object undefined in Internet Explorer 8

如果您尝试JSON.stringify()使用 IE 8,您需要确保它不在兼容模式下工作。请参阅Internet Explorer 8 中未定义的 JSON 对象

You'll need to add

你需要添加

<meta http-equiv="X-UA-Compatible" content="IE=8" />

to your page

到您的页面

回答by Evan Plaice

There's a better solution...

有更好的解决办法...

This doesn't directly answer your question, it provides a complete solution to your problem instead.

这不会直接回答您的问题,而是为您的问题提供完整的解决方案。

The jquery-jsonlibrary provides a wrapper that uses the native JSON object implementation if it's available and falls back to it's own JSON implementation if it isn't. Meaning it'll work in any browser.

jQuery的JSON库提供了一个使用本地JSON对象实现,如果它是可用的,并回落到它自己的JSON实现,如果它不是一个包装。这意味着它可以在任何浏览器中工作。

Here's the Usage Example from the Project's home page:

这是项目主页上的用法示例:

var thing = {plugin: 'jquery-json', version: 2.3};

var encoded = $.toJSON( thing );
// '{"plugin":"jquery-json","version":2.3}'
var name = $.evalJSON( encoded ).plugin;
// "jquery-json"
var version = $.evalJSON(encoded).version;
// 2.3

The usage is very simple: toJSON stringifies the JS source; evalJSON converts JSON string data back to JavaScript objects.

用法很简单:toJSON字符串化JS源码;evalJSON 将 JSON 字符串数据转换回 JavaScript 对象。

Of you look at the source, the implementation is surprisingly simple but it works very well. I have used it personally in a few projects.

你看看源代码,实现非常简单,但效果很好。我在几个项目中亲自使用过它。

There's no need to do browser detection if it works in every browser.

如果它适用于每个浏览器,则无需进行浏览器检测。

回答by atom217

put following code in your js file ;

将以下代码放入您的 js 文件中;

var JSON = JSON || {};

// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function (obj) {

var t = typeof (obj);
if (t != "object" || obj === null) {

    // simple data type
    if (t == "string") obj = '"'+obj+'"';
    return String(obj);

}
else {

    // recurse array or object
    var n, v, json = [], arr = (obj && obj.constructor == Array);

    for (n in obj) {
        v = obj[n]; t = typeof(v);

        if (t == "string") v = '"'+v+'"';
        else if (t == "object" && v !== null) v = JSON.stringify(v);

        json.push((arr ? "" : '"' + n + '":') + String(v));
    }

    return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
}
};

// implement JSON.parse de-serialization
JSON.parse = JSON.parse || function (str) {
if (str === "") str = '""';
eval("var p=" + str + ";");
return p;
 };

回答by saluce

You don't need to use conditionals to determine whether to include json2.jsor not. Take a look at the source code:

您不需要使用条件来确定是否包含json2.js。看一下源代码:

var JSON;
if (!JSON) {
    JSON = {};
}

if (typeof JSON.stringify !== 'function') {
    JSON.stringify = function (value, replacer, space) {
        // Code
    }
}

if (typeof JSON.parse !== 'function') {
    JSON.parse = function (text, reviver) {
        // Code
    }
}

What this does is first check to see if JSONalready exists as an object. If not, then it creates a new object to house the JSON functions. Then, it checks for a native implementation of .stringify()or .parse()exist. If not, then it creates those functions.

它的作用是首先检查是否JSON已经作为对象存在。如果没有,那么它会创建一个新对象来容纳 JSON 函数。然后,它检查.stringify().parse()存在的本机实现。如果没有,那么它会创建这些函数。

Bottom line: if a native implementation exists, including json2.jswill not overwrite the native implementation. Otherwise, it'll add that functionality, so there's no reason you need to use conditionals, unless you are trying to minimize requests.

底线:如果本机实现存在,包括json2.js不会覆盖本机实现。否则,它将添加该功能,因此您没有理由需要使用条件,除非您试图最小化请求。

(It might also be noted that IE10 does not support conditional statements, so I'd recommend against relying on them unless there isn't any alternative.)

(可能还会注意到 IE10 不支持条件语句,因此我建议不要依赖它们,除非没有任何替代方案。)

回答by meder omuraliev

A shiv just createElement's the HTML5 elements. It has nothing to do with JSON. Try getting an actual JSON parser like json2.js from Crockford.

shiv 只是createElementHTML5 元素。它与 JSON 无关。尝试从 Crockford 获取像 json2.js 这样的实际 JSON 解析器。

回答by Jacob Jeske

Just to follow up Mozilla has made a polyfill for the JSON object if you need it to work in IE compatibility mode.

只是为了跟进 Mozilla 已经为 JSON 对象制作了一个 polyfill,如果您需要它在 IE 兼容模式下工作。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON

if (!window.JSON) {
  window.JSON = {
    parse: function(sJSON) { return eval('(' + sJSON + ')'); },
    stringify: (function () {
      var toString = Object.prototype.toString;
      var isArray = Array.isArray || function (a) { return toString.call(a) === '[object Array]'; };
      var escMap = {'"': '\"', '\': '\\', '\b': '\b', '\f': '\f', '\n': '\n', '\r': '\r', '\t': '\t'};
      var escFunc = function (m) { return escMap[m] || '\u' + (m.charCodeAt(0) + 0x10000).toString(16).substr(1); };
      var escRE = /[\"\u0000-\u001F\u2028\u2029]/g;
      return function stringify(value) {
        if (value == null) {
          return 'null';
        } else if (typeof value === 'number') {
          return isFinite(value) ? value.toString() : 'null';
        } else if (typeof value === 'boolean') {
          return value.toString();
        } else if (typeof value === 'object') {
          if (typeof value.toJSON === 'function') {
            return stringify(value.toJSON());
          } else if (isArray(value)) {
            var res = '[';
            for (var i = 0; i < value.length; i++)
              res += (i ? ', ' : '') + stringify(value[i]);
            return res + ']';
          } else if (toString.call(value) === '[object Object]') {
            var tmp = [];
            for (var k in value) {
            if (value.hasOwnProperty(k))
                tmp.push(stringify(k) + ': ' + stringify(value[k]));
            }
             return '{' + tmp.join(', ') + '}';
          }
        }
        return '"' + value.toString().replace(escRE, escFunc) + '"';
      };
    })()
  };
}