mozilla

Revision 589669 of JSON.stringify()

  • Revision slug: Web/JavaScript/Reference/Global_Objects/JSON/stringify
  • Revision title: JSON.stringify()
  • Revision id: 589669
  • Created:
  • Creator: fscholz
  • Is current revision? No
  • Comment

Revision Content

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

Summary

The JSON.stringify() method converts a value to JSON, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.

Syntax

JSON.stringify(value[, replacer [, space]])

Parameters

value
The value to convert to a JSON string.
replacer
If a function, transforms values and properties encountered while stringifying; if an array, specifies the set of properties included in objects in the final string.
A detailed description of the replacer function is provided in the javaScript guide article Using native JSON.
space
Causes the resulting string to be pretty-printed.

Description

JSON.stringify converts an object to JSON notation representing it:

  • Properties of non-array objects are not guaranteed to be stringified in any particular order. Do not rely on ordering of properties within the same object within the stringification.
  • Boolean, Number, and String objects are converted to the corresponding primitive values during stringification, in accord with the traditional conversion semantics.
  • If undefined, a function, or an XML value is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array).
JSON.stringify({});                  // '{}'
JSON.stringify(true);                // 'true'
JSON.stringify("foo");               // '"foo"'
JSON.stringify([1, "false", false]); // '[1,"false",false]'
JSON.stringify({ x: 5 });            // '{"x":5}'
JSON.stringify({x: 5, y: 6});        // '{"x":5,"y":6}' or '{"y":6,"x":5}'

space argument

The space argument may be used to control spacing in the final string. If it is a number, successive levels in the stringification will each be indented by this many space characters (up to 10). If it is a string, successive levels will indented by this string (or the first ten characters of it).

JSON.stringify({ a: 2 }, null, " ");   // '{\n "a": 2\n}'

Using a tab character mimics standard pretty-print appearance:

JSON.stringify({ uno: 1, dos : 2 }, null, '\t')
// returns the string:
// '{            \
//     "uno": 1, \
//     "dos": 2  \
// }' 

toJSON behavior

If an object being stringified has a property named toJSON whose value is a function, then the toJSON method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON method when called will be serialized. For example:

var obj = {
  foo: 'foo',
  toJSON: function () {
    return 'bar';
  }
};
var json = JSON.stringify({x: obj}); // '{"x":"bar"}'.

Example of using JSON.stringify with localStorage

In a case where you want to store an object created by your user and allowing it to be restored even after the browser has been closed, the following example is a model for the applicability of JSON.stringify:

//Creating an example of JSON
var session = {
    'screens' : [],
    'state' : true
};
session.screens.push({"name":"screenA", "width":450, "height":250});
session.screens.push({"name":"screenB", "width":650, "height":350});
session.screens.push({"name":"screenC", "width":750, "height":120});
session.screens.push({"name":"screenD", "width":250, "height":60});
session.screens.push({"name":"screenE", "width":390, "height":120});
session.screens.push({"name":"screenF", "width":1240, "height":650});

// Converting the JSON string with JSON.stringify 
// then saving with localStorage in the name of session
localStorage.setItem('session', JSON.stringify(session));

// Example of how to transform the String generated through 
// JSON.stringify and saved in localStorage in JSON object again
var restoredSession = JSON.parse(localStorage.getItem('session'));

// Now restoredSession variable contains the object that was saved
// in localStorage
console.log(restoredSession);

Specifications

Specification Status Comment
{{SpecName('ES5.1', '#sec-15.12.3', 'JSON.stringify')}} {{Spec2('ES5.1')}} Initial definition.
Implemented in JavaScript 1.7.
{{SpecName('ES6', '#sec-json.stringify', 'JSON.stringify')}} {{Spec2('ES6')}}  

Browser compatibility

{{ CompatibilityTable() }}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support {{ CompatVersionUnknown() }} {{ CompatGeckoDesktop("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 {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatGeckoMobile("1.0") }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }}

Based on Kangax's compat table.

See also

Revision Source

<div>
 {{JSRef("Global_Objects", "JSON")}}</div>
<h2 id="Summary" name="Summary">Summary</h2>
<p>The <code><strong>JSON.stringify()</strong></code> method converts a value to JSON, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.</p>
<h2 id="Syntax" name="Syntax">Syntax</h2>
<pre class="syntaxbox">
<code>JSON.stringify(<em>value</em>[, <em>replacer</em> [, <em>space</em>]])</code></pre>
<h3 id="Parameters" name="Parameters">Parameters</h3>
<dl>
 <dt>
  <code>value</code></dt>
 <dd>
  The value to convert to a JSON string.</dd>
 <dt>
  <code>replacer</code></dt>
 <dd>
  If a function, transforms values and properties encountered while stringifying; if an array, specifies the set of properties included in objects in the final string.<br />
  A detailed description of the <code>replacer</code> function is provided in the javaScript guide article <a href="/en-US/docs/Web/JavaScript/Guide/Using_native_JSON#The_replacer_parameter" title="en/Using native JSON#The_replacer_parameter">Using native JSON</a>.</dd>
 <dt>
  <code>space</code></dt>
 <dd>
  Causes the resulting string to be pretty-printed.</dd>
</dl>
<h2 id="Description">Description</h2>
<p><code>JSON.stringify</code> converts an object to JSON notation representing it:</p>
<ul>
 <li>Properties of non-array objects are not guaranteed to be stringified in any particular order. Do not rely on ordering of properties within the same object within the stringification.</li>
 <li>Boolean, Number, and String objects are converted to the corresponding primitive values during stringification, in accord with the traditional conversion semantics.</li>
 <li>If <code>undefined</code>, a function, or an XML value is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array).</li>
</ul>
<pre class="brush: js">
JSON.stringify({});                  // '{}'
JSON.stringify(true);                // 'true'
JSON.stringify("foo");               // '"foo"'
JSON.stringify([1, "false", false]); // '[1,"false",false]'
JSON.stringify({ x: 5 });            // '{"x":5}'
JSON.stringify({x: 5, y: 6});        // '{"x":5,"y":6}' or '{"y":6,"x":5}'
</pre>
<h3 id="space_argument"><code>space</code> argument</h3>
<p>The space argument may be used to control spacing in the final string. If it is a number, successive levels in the stringification will each be indented by this many space characters (up to 10). If it is a string, successive levels will indented by this string (or the first ten characters of it).</p>
<pre class="brush: js">
JSON.stringify({ a: 2 }, null, " ");   // '{\n "a": 2\n}'</pre>
<p>Using a tab character mimics standard pretty-print appearance:</p>
<pre class="brush: js">
JSON.stringify({ uno: 1, dos : 2 }, null, '\t')
// returns the string:
// '{            \
//&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"uno": 1, \
//&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"dos": 2  \
//&nbsp;}' </pre>
<h3 id="toJSON_behavior">toJSON behavior</h3>
<p>If an object being stringified has a property named <code>toJSON</code> whose value is a function, then the <code>toJSON</code> method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the <code>toJSON</code> method when called will be serialized. For example:</p>
<pre class="brush: js">
var obj = {
  foo: 'foo',
  toJSON: function () {
    return 'bar';
  }
};
var json = JSON.stringify({x: obj}); // <code>'{"x":"bar"}'</code>.
</pre>
<h3 id="Example_of_using_JSON.stringify_with_localStorage">Example of using JSON.stringify with localStorage</h3>
<p>In a case where you want to store an object created by your user and allowing it to be restored even after the browser has been closed, the following example is a model for the applicability of <code>JSON.stringify</code>:</p>
<pre class="brush: js">
//Creating an example of JSON
var session = {
    'screens' : [],
    'state' : true
};
session.screens.push({"name":"screenA", "width":450, "height":250});
session.screens.push({"name":"screenB", "width":650, "height":350});
session.screens.push({"name":"screenC", "width":750, "height":120});
session.screens.push({"name":"screenD", "width":250, "height":60});
session.screens.push({"name":"screenE", "width":390, "height":120});
session.screens.push({"name":"screenF", "width":1240, "height":650});

// Converting the JSON string with JSON.stringify 
// then saving with localStorage in the name of session
localStorage.setItem('session', JSON.stringify(session));

// Example of how to transform the String generated through 
// JSON.stringify and saved in localStorage in JSON object again
var restoredSession = JSON.parse(localStorage.getItem('session'));

// Now restoredSession variable contains the object that was saved
// in localStorage
console.log(restoredSession);
</pre>
<h2 id="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.3', 'JSON.stringify')}}</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td>Initial definition.<br />
    Implemented in JavaScript 1.7.</td>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-json.stringify', 'JSON.stringify')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td>&nbsp;</td>
  </tr>
 </tbody>
</table>
<h2 id="Browser_compatibility">Browser compatibility</h2>
<p>{{ CompatibilityTable() }}</p>
<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>8.0</td>
    <td>10.5</td>
    <td>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="http://kangax.github.com/es5-compat-table/">Kangax's compat table</a>.</p>
<h2 id="See_also">See also</h2>
<ul>
 <li><a href="/en-US/docs/Web/JavaScript/Guide/Using_native_JSON">Using native JSON</a></li>
</ul>
Revert to this revision