Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 766243 of JSON

  • Revision slug: Web/JavaScript/Reference/Global_Objects/JSON
  • Revision title: JSON
  • Revision id: 766243
  • Created:
  • Creator: fscholz
  • Is current revision? No
  • Comment rm link to "Use native JSON" which is old and duplicates this mostly. JSON is native for some time now :)

Revision Content

{{JSRef("Global_Objects", "JSON")}}

Summary

The JSON object contains methods for parsing JavaScript Object Notation ({{glossary("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 {{jsxref("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; a decimal point must be followed by at least one digit.
Strings

Only a limited sets 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 {{jsxref("JSON.parse()")}} works fine and a {{jsxref("SyntaxError")}} is thrown when evaluating the code as JavaScript:

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

The full JSON syntax is as follows:

JSON = null
    or true or false
    or JSONNumber
    or JSONString
    or JSONObject
    or JSONArray

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

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

JSONObject = { }
          or { Members }
Members = JSONString : JSON
       or Members , JSONString : JSON

JSONArray = [ ]
         or [ ArrayElements ]
ArrayElements = JSON
             or ArrayElements , JSON

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

{{jsxref("JSON.parse()")}}
Parse a string as JSON, optionally transform the produced value and its properties, and return the value.
{{jsxref("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:

if (!window.JSON) {
  window.JSON = {
    parse: function(sJSON) { return eval('(' + sJSON + ')'); },
    stringify: function(vContent) {
      if (vContent instanceof Object) {
        var sOutput = '';
        if (vContent.constructor === Array) {
          for (var nId = 0; nId < vContent.length; sOutput += this.stringify(vContent[nId]) + ',', nId++);
          return '[' + sOutput.substr(0, sOutput.length - 1) + ']';
        }
        if (vContent.toString !== Object.prototype.toString) {
          return '"' + vContent.toString().replace(/"/g, '\\$&') + '"';
        }
        for (var sProp in vContent) {
          sOutput += '"' + sProp.replace(/"/g, '\\$&') + '":' + this.stringify(vContent[sProp]) + ',';
        }
        return '{' + sOutput.substr(0, sOutput.length - 1) + '}';
     }
     return typeof vContent === 'string' ? '"' + vContent.replace(/"/g, '\\$&') + '"' : String(vContent);
    }
  };
}

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

Specifications

Specification Status Comment
{{SpecName('ES5.1', '#sec-15.12', 'JSON')}} {{Spec2('ES5.1')}}  
{{SpecName('ES6', '#sec-json-object', 'JSON')}} {{Spec2('ES6')}}  

Browser compatibility

{{CompatibilityTable}}
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support {{CompatVersionUnknown}} {{CompatGeckoDesktop("1.9.1")}} {{CompatIE("8.0")}} {{CompatOpera("10.5")}} {{CompatSafari("4.0")}}
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatGeckoMobile("1.0")}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}}

Based on Kangax's compat table.

See also

  • {{jsxref("Date.prototype.toJSON()")}}

Revision Source

<div>{{JSRef("Global_Objects", "JSON")}}</div>

<h2 id="Summary" name="Summary">Summary</h2>

<p>The <strong><code>JSON</code></strong> object contains methods for parsing <a class="external" href="https://json.org/">JavaScript Object Notation</a> ({{glossary("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.</p>

<h2 id="Description" name="Description">Description</h2>

<h3 id="JavaScript_Object_Notation" name="JavaScript_Object_Notation">JavaScript Object Notation</h3>

<p>JSON is a syntax for serializing objects, arrays, numbers, strings, booleans, and {{jsxref("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 <a href="https://timelessrepo.com/json-isnt-a-javascript-subset">JSON: The JavaScript subset that isn't</a>.</p>

<table align="left">
 <caption>JavaScript and JSON differences</caption>
 <thead>
  <tr>
   <th scope="col">JavaScript type</th>
   <th scope="col">JSON differences</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>Objects and Arrays</td>
   <td>Property names must be double-quoted strings; trailing commas are forbidden.</td>
  </tr>
  <tr>
   <td>Numbers</td>
   <td>Leading zeros are prohibited; a decimal point must be followed by at least one digit.</td>
  </tr>
  <tr>
   <td>Strings</td>
   <td>
    <p>Only a limited sets of characters may be escaped; certain control characters are prohibited; the Unicode line separator (<a href="https://unicode-table.com/en/2028/">U+2028</a>) and paragraph separator (<a href="https://unicode-table.com/en/2029/">U+2029</a>) characters are permitted; strings must be double-quoted. See the following example where {{jsxref("JSON.parse()")}} works fine and a {{jsxref("SyntaxError")}} is thrown when evaluating the code as JavaScript:</p>

    <pre class="brush: js">
var code = '"\u2028\u2029"';
JSON.parse(code); // works fine
eval(code); // fails
</pre>
   </td>
  </tr>
 </tbody>
</table>

<p>The full JSON syntax is as follows:</p>

<pre>
<var>JSON</var> = <strong>null</strong>
    <em>or</em> <strong>true</strong> <em>or</em> <strong>false</strong>
    <em>or</em> <var>JSONNumber</var>
    <em>or</em> <var>JSONString</var>
    <em>or</em> <var>JSONObject</var>
    <em>or</em> <var>JSONArray</var>

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

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

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

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

<p>Insignificant whitespace may be present anywhere except within a <code><var>JSONNumber</var></code> (numbers must contain no whitespace) or <code><var>JSONString</var></code> (where it is interpreted as the corresponding character in the string, or would cause an error). The tab character (<a href="https://unicode-table.com/en/0009/">U+0009</a>), carriage return (<a href="https://unicode-table.com/en/000D/">U+000D</a>), line feed (<a href="https://unicode-table.com/en/000A/">U+000A</a>), and space (<a href="https://unicode-table.com/en/0020/">U+0020</a>) characters are the only valid whitespace characters.</p>

<h2 id="Methods" name="Methods">Methods</h2>

<dl>
 <dt>{{jsxref("JSON.parse()")}}</dt>
 <dd>Parse a string as JSON, optionally transform the produced value and its properties, and return the value.</dd>
 <dt>{{jsxref("JSON.stringify()")}}</dt>
 <dd>Return a JSON string corresponding to the specified value, optionally including only certain properties or replacing property values in a user-defined manner.</dd>
</dl>

<h2 id="Polyfill" name="Polyfill">Polyfill</h2>

<p>The <code>JSON</code> 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 <code>JSON</code> object in implementations which do not natively support it (like Internet Explorer 6).</p>

<p>The following algorithm is an imitation of the native <code>JSON</code> object:</p>

<pre class="brush: js">
if (!window.JSON) {
  window.JSON = {
    parse: function(sJSON) { return eval('(' + sJSON + ')'); },
    stringify: function(vContent) {
      if (vContent instanceof Object) {
        var sOutput = '';
        if (vContent.constructor === Array) {
          for (var nId = 0; nId &lt; vContent.length; sOutput += this.stringify(vContent[nId]) + ',', nId++);
          return '[' + sOutput.substr(0, sOutput.length - 1) + ']';
        }
        if (vContent.toString !== Object.prototype.toString) {
          return '"' + vContent.toString().replace(/"/g, '\\$&amp;') + '"';
        }
        for (var sProp in vContent) {
          sOutput += '"' + sProp.replace(/"/g, '\\$&amp;') + '":' + this.stringify(vContent[sProp]) + ',';
        }
        return '{' + sOutput.substr(0, sOutput.length - 1) + '}';
     }
     return typeof vContent === 'string' ? '"' + vContent.replace(/"/g, '\\$&amp;') + '"' : String(vContent);
    }
  };
}
</pre>

<p>More complex well-known <a class="external" href="https://remysharp.com/2010/10/08/what-is-a-polyfill/">polyfills</a> for the <code>JSON</code> object are <a class="link-https" href="https://github.com/douglascrockford/JSON-js">JSON2</a> and <a class="external" href="https://bestiejs.github.com/json3">JSON3</a>.</p>

<h2 id="Specifications" name="Specifications">Specifications</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('ES5.1', '#sec-15.12', 'JSON')}}</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td>&nbsp;</td>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-json-object', 'JSON')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td>&nbsp;</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility" name="Browser_compatibility">Browser compatibility</h2>

<div>{{CompatibilityTable}}</div>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatGeckoDesktop("1.9.1")}}</td>
   <td>{{CompatIE("8.0")}}</td>
   <td>{{CompatOpera("10.5")}}</td>
   <td>{{CompatSafari("4.0")}}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Chrome for Android</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatGeckoMobile("1.0")}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<p>Based on <a class="external" href="https://kangax.github.com/es5-compat-table/">Kangax's compat table</a>.</p>

<h2 id="See_also" name="See_also">See also</h2>

<ul>
 <li>{{jsxref("Date.prototype.toJSON()")}}</li>
</ul>
Revert to this revision