JSON

  • 版本网址缩略名: JSON
  • 版本标题: JSON
  • 版本 id: 405613
  • 创建于:
  • 创建者: Will_Chen
  • 是否是当前版本?
  • 评论

修订内容

JSON (JavaScript Object Notation)  is a data-interchange format.  It closely resembles a subset of JavaScript syntax, although it is not a strict subset. (See JSON in the JavaScript Reference for full details.)  It is useful when writing any kind of JavaScript-based application, including websites and browser extensions.  For example, you might store user information in JSON format in a cookie, or you might store extension preferences in JSON in a string-valued browser preference.

JSON is capable of representing numbers, booleans, strings, null, and arrays (ordered sequences of values) and objects (string-value mappings) composed of these values (or of other arrays and objects).  It doesn't natively represent more complex data types like functions, regular expressions, dates, and so on.  (Date objects by default serialize as a string containing the date in ISO format, so while they don't round-trip, the information isn't completely lost.)  If you need to preserve such values, you can transform values as they are serialized, or prior to deserialization, to enable JSON to represent additional data types.

Documentation

JSON object
The JSON object contains methods for converting values to JavaScript Object Notation (JSON) and for converting JSON to values.
Using native JSON
This article covers the ECMAScript 5 compliant native JSON object added in Gecko 1.9.1.
JSONPath
JSONPath is a means of using XPath-like syntax to query JSON structures. It is not a standard, but it does offer a means of querying JavaScript structures directly without needing to convert to or from XML.
Downloading JSON and JavaScript in extensions
A common practice found in many extensions is using XMLHttpRequest (or some other mechanism) to download JavaScript or JSON (they are different) from a remote website. Once the content has been downloaded, the extension authors proceed to use eval() to decode the string content into JavaScript objects, which is a dangerous practice and will not, in fact, pass an AMO review. This article shows how to avoid it.
JXON
JXON stands for lossless Javascript XML Object Notation, it is a generic name by which is defined the representation of Javascript object trees (JSON) using XML.
JSON.stringify method
Convert 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.
JSON.parse method
Parse a string as JSON, optionally transforming the value produced by parsing.

View All...

Community

  • View Mozilla forums...

{{ DiscussionList("dev-tech-json", "mozilla.dev.tech.json") }}

Tools

View All...

AJAX, JavaScript, XUL

Using JSON through JavaScript's JSON object

The simplest, easiest way to use JSON is through the standard JSON object in JavaScript.  Use JSON.stringify to serialize a JSON value, and use JSON.parse to deserialize a JSON value.

For example, to serialize a JavaScript object, use the JSON.stringify() method:

var foo = {};
foo.bar = "new property";
foo.baz = 3;

var JSONfoo = JSON.stringify(foo);

JSONfoo now holds {"bar":"new property","baz":3}. To make JSONfoo back into a JavaScript object just do:

var backToJS = JSON.parse(JSONfoo);

For more information, see the JSON object documentation.

toJSON() method

If an object defines a toJSON() method, JSON.stringify will call that method to determine the object's JSON representation. For example:

x = {}; 
x.foo = "foo";  
x.toJSON = function() { return "bar"; }; 
var json1 = JSON.stringify(x); 

json1 now contains '"bar"'.

Limitations

You cannot serialize an object that has members which are functions. The JSON specification does not allow it. For example:

foo.qwerty = function(){alert('foobar');}; 
foo.qwerty() 
var JSONfoo = JSON.toString(foo); 

will raise a TypeError on line XXX: No JSON representation for this object!

Using JSON through nsIJSON

Versions of Firefox before 3.5 don't natively support JSON, and the only way to access JSON functionality is through the nsIJSON component, implemented since Firefox 3.  Encoding and decoding are performed through nsIJSON's encode and decode methods.  These methods are not as powerful as JSON through the JSON object, and they only support values which are objects or arrays, not strings, booleans, numbers, or null.  (These values are only supported within arrays and objects: the plain number 5 will not work, but the object { "value": 5 } will.)

Because nsIJSON is not as powerful as the JSON object, its encode and decode methods have been removed from Firefox 7.  Developers should switch to using the JSON object instead.

The following code serializes a JavaScript object using nsIJSON:

var Ci = Components.interfaces;
var Cc = Components.classes;

var foo = {};
foo.bar = "new property";
foo.baz = 3;

var nativeJSON = Cc["@mozilla.org/dom/json;1"].createInstance(Ci.nsIJSON);
var JSONfoo = nativeJSON.encode(foo);

The JSONfoo variable now holds the string {"bar":"new property","baz":3}. To create an object corresponding to JSONfoo, just do:

var backToJS = nativeJSON.decode(JSONfoo);

Using JSON in other ways

While in theory it's possible to use JSON by using eval (but only to deserialize to an object, and not to serialize to a string) or by using json2.js, it's not a good idea.  It's not safe to parse JSON using eval because eval permits much more syntax than JSON does (up to arbitrary code execution).  As for json2.js, its problem is that it adds methods to built-in objects like Object.prototype, which is very likely to break code not specifically anticipating that possibility.  You should almost always use either of the former methods to use JSON in preference to any other way.  

See also

  • {{ interface("nsIJSON") }}

{{ languages( { "ja": "ja/JSON", "zh-cn": "zh-cn/JSON" } ) }}

修订版来源

<p><strong>JSON</strong> (<strong>JavaScript Object Notation</strong>)&nbsp; is a data-interchange format. &nbsp;It closely resembles a subset of <a href="/en/JavaScript" title="en/JavaScript">JavaScript</a> syntax, although it is not a strict subset. (See <a href="/en/JavaScript/Reference/Global_Objects/JSON" title="en/JavaScript/Reference/Global Objects/JSON">JSON</a> in the <a href="/en/JavaScript/Reference" title="en/JavaScript/Reference">JavaScript Reference</a> for full details.) &nbsp;It is useful when writing any kind of JavaScript-based application, including websites and browser extensions. &nbsp;For example, you might store user information in JSON format in a <a href="/en/DOM/document.cookie" title="en/document.cookie">cookie</a>, or you might store extension preferences in JSON in a string-valued browser preference.</p>
<p>JSON is capable of representing numbers, booleans, strings, <code>null</code>, and arrays (ordered sequences of values) and objects (string-value mappings) composed of these values (or of other arrays and objects). &nbsp;It doesn't natively represent more complex data types like functions, regular expressions, dates, and so on. &nbsp;(Date objects by default serialize as a string containing the date in ISO&nbsp;format, so while they don't round-trip, the information isn't completely lost.)&nbsp; If you need to preserve such values, you can transform values as they are serialized, or prior to deserialization, to enable JSON to represent additional data types.</p>
<table class="topicpage-table">
  <tbody>
    <tr>
      <td>
        <h4 id="Documentation" name="Documentation"><a href="/Special:Tags?tag=JSON&amp;language=en" title="Pages tagged with: JSON">Documentation</a></h4>
        <dl>
          <dt>
            <a href="/en/JavaScript/Reference/Global_Objects/JSON" title="en/JavaScript/Reference/Global_Objects/JSON"><code>JSON</code> object</a></dt>
          <dd>
            <small>The <code>JSON</code> object contains methods for converting values to <a class="external" href="http://json.org/">JavaScript Object Notation</a> (JSON) and for converting JSON to values.</small></dd>
        </dl>
        <dl>
          <dt>
            <a href="/en/Using_native_JSON" title="en/Using_native_JSON">Using native JSON</a></dt>
          <dd>
            <small>This article covers the ECMAScript 5 compliant native JSON object added in Gecko 1.9.1.</small></dd>
        </dl>
        <dl>
          <dt>
            <a href="/en/JSON/JSONPath" title="en/JSON/JSONPath">JSONPath</a></dt>
          <dd>
            <small>JSONPath is a means of using XPath-like syntax to query JSON structures. It is not a standard, but it does offer a means of querying JavaScript structures directly without needing to convert to or from XML.</small></dd>
        </dl>
        <dl>
          <dt>
            <a href="/en/Downloading_JSON_and_JavaScript_in_extensions" title="en/Downloading_JSON_and_JavaScript_in_extensions">Downloading JSON and JavaScript in extensions</a></dt>
          <dd>
            <small>A common practice found in many extensions is using <a href="/en/DOM/XMLHttpRequest" title="en/DOM/XMLHttpRequest">XMLHttpRequest</a> (or some other mechanism) to download JavaScript or <a href="/en/JSON" title="en/JSON">JSON</a> (they are different) from a remote website. Once the content has been downloaded, the extension authors proceed to use <code><a href="/en/Core_JavaScript_1.5_Reference/Functions/eval" title="en/Core_JavaScript_1.5_Reference/Functions/eval"> eval()</a></code> to decode the string content into JavaScript objects, which is a <strong>dangerous</strong> practice and will not, in fact, pass an <a class="external" href="http://addons.mozilla.org">AMO</a> review. This article shows how to avoid it.</small></dd>
        </dl>
        <dl>
          <dt>
            <a href="/en/JXON" title="en/JXON">JXON</a></dt>
          <dd>
            <small>JXON stands for lossless <strong>J</strong>avascript <strong>X</strong>ML <strong>O</strong>bject <strong>N</strong>otation, it is a generic name by which is defined the representation of Javascript object trees (JSON) using XML.</small></dd>
        </dl>
        <dl>
          <dt>
            <a href="/en/JavaScript/Reference/Global_Objects/JSON/stringify" title="en/JavaScript/Reference/Global_Objects/JSON/stringify"><code>JSON.stringify</code> method</a></dt>
          <dd>
            <small>Convert 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.</small></dd>
        </dl>
        <dl>
          <dt>
            <a href="/en/JavaScript/Reference/Global_Objects/JSON/parse" title="en/JavaScript/Reference/Global_Objects/JSON/parse"><code>JSON.parse</code> method</a></dt>
          <dd>
            <small>Parse a string as JSON, optionally transforming the value produced by parsing.</small></dd>
        </dl>
        <p><span class="alllinks"><a href="/Special:Tags?tag=JSON&amp;language=en" title="Pages tagged with: JSON">View All...</a></span></p>
      </td>
      <td>
        <h4 id="Community" name="Community">Community</h4>
        <ul>
          <li>View Mozilla forums...</li>
        </ul>
        <p>{{ DiscussionList("dev-tech-json", "mozilla.dev.tech.json") }}</p>
        <h4 id="Tools" name="Tools">Tools</h4>
        <ul>
          <li><a class="internal" href="/en/JavaScript/Reference/Global_Objects/JSON#Browser_compatibility" title="JSON object polyfills">JSON polyfills</a></li>
          <li><a class="external" href="http://jsonselect.org" title="http://jsonselect.org/">JSONSelect</a></li>
        </ul>
        <p><span class="alllinks"><a href="/Special:Tags?tag=JSON:Tools&amp;language=en" title="Pages tagged with: JSON:Tools">View All...</a></span></p>
        <h4 id="Related_Topics" name="Related_Topics">Related Topics</h4>
        <dl>
          <dd>
            <a href="/en/AJAX" title="en/AJAX">AJAX</a>, <a href="/en/JavaScript" title="en/JavaScript">JavaScript</a>, <a href="/en/XUL" title="en/XUL">XUL</a></dd>
        </dl>
      </td>
    </tr>
  </tbody>
</table>
<h2 id="JSON_in_Firefox_2" name="JSON_in_Firefox_2">Using JSON through JavaScript's JSON object</h2>
<p>The simplest, easiest way to use JSON is through the standard <a href="/en/JavaScript/Reference/Global_Objects/JSON" title="en/JavaScript/Reference/Global Objects/JSON">JSON object</a> in JavaScript. &nbsp;Use <a href="/en/JavaScript/Reference/Global_Objects/JSON/stringify" title="en/JavaScript/Reference/Global Objects/JSON/stringify">JSON.stringify</a> to serialize a JSON value, and use <a href="/en/JavaScript/Reference/Global_Objects/JSON/parse" title="en/JavaScript/Reference/Global Objects/JSON/parse">JSON.parse</a> to deserialize a JSON value.</p>
<p>For example, to serialize a JavaScript object, use the <code>JSON.stringify()</code> method:</p>
<pre class="brush: js">
var foo = {};
foo.bar = "new property";
foo.baz = 3;

var JSONfoo = JSON.stringify(foo);
</pre>
<p><code>JSONfoo</code> now holds <code>{"bar":"new property","baz":3}</code>. To make <code>JSONfoo</code> back into a JavaScript object just do:</p>
<pre class="brush: js">
var backToJS = JSON.parse(JSONfoo);
</pre>
<p>For more information, see the <a href="/en/JavaScript/Reference/Global_Objects/JSON" title="en/JavaScript/Reference/Global Objects/JSON">JSON object</a> documentation.</p>
<h2 id="toJSON()_method">toJSON() method</h2>
<p>If an object defines a toJSON() method, JSON.stringify will call that method to determine the object's JSON representation. For example:</p>
<pre class="brush: js">
x = {}; 
x.foo = "foo"; &nbsp;
x.toJSON = function() { return "bar"; }; 
var json1 = JSON.stringify(x); 
</pre>
<p><code>json1</code> now contains '"bar"'.</p>
<h2 id="Limitations">Limitations</h2>
<p>You cannot serialize an object that has members which are <code>functions</code>. The JSON specification does not allow it. For example:</p>
<pre class="brush: js">
foo.qwerty = function(){alert('foobar');}; 
foo.qwerty() 
var JSONfoo = JSON.toString(foo); 
</pre>
<p>will raise a <code>TypeError on line XXX: No JSON representation for this object!</code></p>
<h2 id="Using_JSON_through_nsIJSON">Using JSON through nsIJSON</h2>
<p>Versions of Firefox before 3.5 don't natively support JSON, and the only way to access JSON functionality is through the <code><a href="/en/XPCOM_Interface_Reference/nsIJSON" title="en/nsIJSON">nsIJSON</a></code> component, implemented since Firefox 3. &nbsp;Encoding and decoding are performed through <code>nsIJSON</code>'s <code>encode</code> and <code>decode</code> methods. &nbsp;These methods are not as powerful as JSON through the JSON object, and they only support values which are objects or arrays, not strings, booleans, numbers, or <code>null</code>. &nbsp;(These values are only supported within arrays and objects: the plain number <code>5</code> will not work, but the object <code>{ "value": 5 }</code> will.)</p>
<p>Because nsIJSON is not as powerful as the JSON object, its encode and decode methods have been removed from Firefox 7. &nbsp;Developers should switch to using the JSON object instead.</p>
<p>The following code serializes a JavaScript object using <code>nsIJSON</code>:</p>
<pre class="brush: js">
var Ci = Components.interfaces;
var Cc = Components.classes;

var foo = {};
foo.bar = "new property";
foo.baz = 3;

var nativeJSON = Cc["@mozilla.org/dom/json;1"].createInstance(Ci.nsIJSON);
var JSONfoo = nativeJSON.encode(foo);
</pre>
<p>The <code>JSONfoo</code> variable now holds the string <code>{"bar":"new property","baz":3}</code>. To create an object corresponding to <code>JSONfoo</code>, just do:</p>
<pre class="brush: js">
var backToJS = nativeJSON.decode(JSONfoo);
</pre>
<h2 id="Using_JSON" name="Using_JSON">Using JSON in other ways</h2>
<p>While in theory it's possible to use JSON by using <a href="/en/JavaScript/Reference/Global_Objects/eval" title="en/JavaScript/Reference/Global Objects/eval">eval</a> (but only to deserialize to an object, and not to serialize to a string) or by using <a class="link-https" href="https://github.com/douglascrockford/JSON-js" title="https://github.com/douglascrockford/JSON-js">json2.js</a>, it's not a good idea. &nbsp;It's not safe to parse JSON using eval because eval permits much more syntax than JSON does (up to arbitrary code execution). &nbsp;As for json2.js, its problem is that it adds methods to built-in objects like <code>Object.prototype</code>, which is very likely to break code not specifically anticipating that possibility. &nbsp;You should almost always use either of the former methods to use JSON in preference to any other way.&nbsp;&nbsp;</p>
<h2 id="See_also" name="See_also">See also</h2>
<ul>
  <li>{{ interface("nsIJSON") }}</li>
</ul>
<p>{{ languages( { "ja": "ja/JSON", "zh-cn": "zh-cn/JSON" } ) }}</p>
恢复到这个版本