IT TIP

IE 8에서 JSON.stringify ()를 지원합니까?

itqueen 2020. 12. 10. 21:36
반응형

IE 8에서 JSON.stringify ()를 지원합니까?


다음을 사용해야합니다.

JSON.stringify()

Chrome, Safari 및 Firefox에서 지원되어야합니다. IE8도 JSON 개체를 지원한다고 생각합니다. IE7과 6은 그렇지 않다고 생각합니다.

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

따라서 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]-->

그래서 IE 8에도 이것을 포함해야합니까?


제목의 질문에 직접 답하려면 IE8이 JSON.stringify()기본적으로 지원합니다 .

IE8은이 지원을받는 최초의 IE 버전이며, 여기에서 개발 팀이 기능에 대해 자세히 설명합니다. http://blogs.msdn.com/b/ie/archive/2008/09/10/native-json -in-ie8.aspx

질문의 두 번째 부분에 대한 대답은 예, IE6 / IE7에 대한 대체 기능을 포함해야합니다. Modernizr와 같은 것이 이것을 쉽게 확인할 수 있습니다.

또한 사용자가 IE8의 호환성보기에있는 경우 JSON 개체를 사용할 수 없습니다.


JSON.stringify()IE 8을 사용 하려는 경우 호환 모드에서 작동하지 않는지 확인해야합니다. Internet Explorer 8에서 정의되지 않은 JSON 개체 참조

추가해야합니다.

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

귀하의 페이지로


더 나은 해결책이 있습니다 ...

이것은 귀하의 질문에 직접 답하는 것이 아니라 귀하의 문제에 대한 완전한 해결책을 제공합니다.

JQuery와-json으로 라이브러리는 사용할 수하고, 그렇지 않은 경우는 자신의 JSON 구현의 위로 떨어지는 경우 네이티브 JSON 객체 구현을 사용하는 래퍼를 제공합니다. 모든 브라우저에서 작동한다는 의미입니다.

다음은 프로젝트 홈 페이지의 사용 예입니다.

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

사용법은 매우 간단합니다. toJSON은 JS 소스를 문자열 화합니다. evalJSON은 JSON 문자열 데이터를 JavaScript 객체로 다시 변환합니다.

소스를 보면 구현이 놀랍도록 간단하지만 매우 잘 작동합니다. 저는 몇 가지 프로젝트에서 개인적으로 사용했습니다.

모든 브라우저에서 작동한다면 브라우저 감지를 수행 할 필요가 없습니다.


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;
 };

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 JSON already 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.

Bottom line: if a native implementation exists, including json2.js will 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.

(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.)


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.


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

참고URL : https://stackoverflow.com/questions/3326893/is-json-stringify-supported-by-ie-8

반응형