Is JSON.stringify() supported by IE 8?

后端 未结 7 922
情歌与酒
情歌与酒 2020-11-27 05:32

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.

7条回答
  •  离开以前
    2020-11-27 05:46

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

    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) + '"';
          };
        })()
      };
    }
    

提交回复
热议问题