JSON

The JSON object contains methods for parsing JavaScript Object Notation (JSON) and converting values to JSON. It can't be called or constructed, and aside from its two method properties it has no interesting functionality of its own.

Description

JavaScript Object Notation

JSON is a syntax for serializing objects, arrays, numbers, strings, booleans, and null. It is based upon JavaScript syntax but is distinct from it: some JavaScript is not JSON, and some JSON is not JavaScript. See also JSON: The JavaScript subset that isn't.

JavaScript and JSON differences
JavaScript type JSON differences
Objects and Arrays Property names must be double-quoted strings; trailing commas are forbidden.
Numbers Leading zeros are prohibited( in JSON.stringify zeros will be ignored, but in JSON.parse it will throw SyntaxError); a decimal point must be followed by at least one digit.
Strings

Only a limited set of characters may be escaped; certain control characters are prohibited; the Unicode line separator (U+2028) and paragraph separator (U+2029) characters are permitted; strings must be double-quoted. See the following example where JSON.parse() works fine and a SyntaxError is thrown when evaluating the code as JavaScript:

JavaScript
var code = '"\u2028\u2029"';
JSON.parse(code); // works fine
eval(code); // fails

The full JSON syntax is as follows:

JavaScript
<var>JSON</var> = null
    or true or false
    or <var>JSONNumber</var>
    or <var>JSONString</var>
    or <var>JSONObject</var>
    or <var>JSONArray</var>

<var>JSONNumber</var> = - <var>PositiveNumber</var>
          or <var>PositiveNumber</var>
<var>PositiveNumber</var> = DecimalNumber
              or <var>DecimalNumber</var> . <var>Digits</var>
              or <var>DecimalNumber</var> . <var>Digits</var> <var>ExponentPart</var>
              or <var>DecimalNumber</var> <var>ExponentPart</var>
<var>DecimalNumber</var> = 0
             or <var>OneToNine</var> <var>Digits</var>
<var>ExponentPart</var> = e <var>Exponent</var>
            or E <var>Exponent</var>
<var>Exponent</var> = <var>Digits</var>
        or + <var>Digits</var>
        or - <var>Digits</var>
<var>Digits</var> = <var>Digit</var>
      or <var>Digits</var> <var>Digit</var>
<var>Digit</var> = 0 through 9
<var>OneToNine</var> = 1 through 9

<var>JSONString</var> = ""
          or " <var>StringCharacters</var> "
<var>StringCharacters</var> = <var>StringCharacter</var>
                or <var>StringCharacters</var> <var>StringCharacter</var>
<var>StringCharacter</var> = any character
                  except " or \ or U+0000 through U+001F
               or <var>EscapeSequence</var>
<var>EscapeSequence</var> = \" or \/ or \\ or \b or \f or \n or \r or \t
              or \u <var>HexDigit</var> <var>HexDigit</var> <var>HexDigit</var> <var>HexDigit</var>
<var>HexDigit</var> = 0 through 9
        or A through F
        or a through f

<var>JSONObject</var> = { }
          or { <var>Members</var> }
<var>Members</var> = <var>JSONString</var> : <var>JSON</var>
       or <var>Members</var> , <var>JSONString</var> : <var>JSON</var>

<var>JSONArray</var> = [ ]
         or [ <var>ArrayElements</var> ]
<var>ArrayElements</var> = <var>JSON</var>
             or <var>ArrayElements</var> , <var>JSON</var>

Insignificant whitespace may be present anywhere except within a JSONNumber (numbers must contain no whitespace) or JSONString (where it is interpreted as the corresponding character in the string, or would cause an error). The tab character (U+0009), carriage return (U+000D), line feed (U+000A), and space (U+0020) characters are the only valid whitespace characters.

Methods

JSON.parse()
Parse a string as JSON, optionally transform the produced value and its properties, and return the value.
JSON.stringify()
Return a JSON string corresponding to the specified value, optionally including only certain properties or replacing property values in a user-defined manner.

Polyfill

The JSON object is not supported in older browsers. You can work around this by inserting the following code at the beginning of your scripts, allowing use of JSON object in implementations which do not natively support it (like Internet Explorer 6).

The following algorithm is an imitation of the native JSON object:

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

More complex well-known polyfills for the JSON object are JSON2 and JSON3.

Specifications

Specification Status Comment
ECMAScript 5.1 (ECMA-262)
The definition of 'JSON' in that specification.
Standard Initial definition.
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'JSON' in that specification.
Standard  
ECMAScript 2017 Draft (ECMA-262)
The definition of 'JSON' in that specification.
Draft  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) 3.5 (1.9.1) 8.0 10.5 4.0
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) 1.0 (1.0) (Yes) (Yes) (Yes)

See also

License

© 2016 Mozilla Contributors
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/json

JavaScript JSON Object polyfill Reference Référence