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 1116655 of Working with JSON data

  • Revision slug: Learn/JavaScript/Objects/JSON
  • Revision title: Working with JSON data
  • Revision id: 1116655
  • Created:
  • Creator: chrisdavidmills
  • Is current revision? No
  • Comment

Revision Content

{{draft}}{{LearnSidebar}}
{{PreviousMenuNext("Learn/JavaScript/Objects/Basics", "Learn/JavaScript/Objects/Object-oriented_JS", "Learn/JavaScript/Objects")}}

JavaScript Object Notation (JSON) is a standard format for representing structured data as JavaScript objects, which is commonly used for representing and transmitting data on web sites (i.e. sending some data from the server to the client, so it can be displayed on a web page). You'll come across it quite often, so in this article we give you all you need to work with JSON using JavaScript, including accessing data items in a JSON object and writing your own JSON.

Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, familiarity with JavaScript basics (see First steps and Building blocks) and OOJS basics (see Introduction to objects).
Objective: To understand how to work with data stored in JSON, and create your own JSON objects.

No, really, what is JSON?

{{glossary("JSON")}} is a data format following JavaScript object syntax, which was popularized by Douglas Crockford. Even though it is based on JavaScript syntax, it can be used independently from JavaScript, and many programming environments feature the ability to read (parse) and generate JSON.

JSON can exist as an object, or a string — the former is used when you want to read data out of the JSON, and the latter is used when you want to send the JSON across the network. This is not a big issue —  JavaScript provides a global JSON object that has methods available for converting between the two.

A JSON object can be stored in its own file, which is basically just a text file with an extension of .json, and a {{glossary("MIME type")}} of application/json.

JSON structure

We've implied above that a JSON object is basically a JavaScript object, and this is mostly right. You can include the same basic data types inside JSON as you can in a standard JavaScript object — strings, numbers, arrays, booleans, and other object literals. This allows you to construct a data hierarchy, like so:

{
  "squadName" : "Super hero squad",
  "homeTown" : "Metro City",
  "formed" : 2016,
  "secretBase" : "Super tower",
  "active" : true,
  "members" : [
    {
      "name" : "Molecule Man",
      "age" : 29,
      "secretIdentity" : "Dan Jukes",
      "powers" : [
        "Radiation resistance",
        "Turning tiny",
        "Radiation blast"
      ]
    },
    {
      "name" : "Madame Uppercut",
      "age" : 39,
      "secretIdentity" : "Jane Wilson",
      "powers" : [
        "Million tonne punch",
        "Damage resistance",
        "Superhuman reflexes"
      ]
    },
    {
      "name" : "Eternal Flame",
      "age" : 1000000,
      "secretIdentity" : "Unknown",
      "powers" : [
        "Immortality",
        "Heat Immunity",
        "Inferno",
        "Teleportation",
        "Interdimensional travel"
      ]
    }
  ]
}

If we loaded this object into a JavaScript program, saved in a variable called superHeroes for example, we could then access the data inside it using the same dot/bracket notation we looked at in the last article. For example:

superHeroes.hometown
superHeroes["active"]

To access data further down the hierarchy, you simply have to chain the required property names and array indexes together.  For example, to access the third superpower of the second hero listed in the members list, you'd do this:

superHeroes["members"][1]["powers"][2]
  1. First we have the variable name — superHeroes.
  2. Inside that we want to access the members property, so we use ["members"].
  3. members contains an array populated by objects. We want to access the second object inside the array, so we use [1].
  4. Inside this object, we want to access the powers property, so we use ["powers"].
  5. Inside the powers property is an array containing the selected hero's superpowers. We want the third one, so we use [2].

Note: We've made the JSON seen above available inside a variable in our JSONText.html example (see source code). Try loading this up and then accessing data inside the variable via your browser's JavaScript console.

Arrays as JSON

Above we said "We've implied above that a JSON object is basically a JavaScript object, and this is mostly right" — the reason we said "mostly right" is because an array can also be a valid JSON object, for example:

[
  {
    "name" : "Molecule Man",
    "age" : 29,
    "secretIdentity" : "Dan Jukes",
    "powers" : [
      "Radiation resistance",
      "Turning tiny",
      "Radiation blast"
    ]
  },
  {
    "name" : "Madame Uppercut",
    "age" : 39,
    "secretIdentity" : "Jane Wilson",
    "powers" : [
      "Million tonne punch",
      "Damage resistance",
      "Superhuman reflexes"
    ]
  }
]

The above is perfectly valid JSON. You'd just have to access array items by starting with an array index, for example [0]["powers"][0].

Other notes

  • JSON is purely a data format — it contains only properties, no methods.
  • JSON requires double quotes to be used to be valid. It is safest to write it with double quotes, not single quotes.
  • Even a single misplaced comma or colon can cause a JSON file to go wrong, and not work. You should be careful to validate any data you are attempting to use (although computer-generated JSON is less likely to include errors, as long as the generator program is working correctly). You can validate JSON using an application like JSONLint.
  • JSON can actually take the form of any data type that is valid for inclusion inside a standard JSON object, not just arrays or objects. So for example, a single string or number would be a valid JSON object. Not that this would be particularly useful...

Active learning: Working through a JSON example

 

Summary

In this article, we've given you a simple guide to using JSON in your programs, including how to create and parse JSON, and how to access data locked inside it. In the next article we'll begin looking at object oriented JavaScript.

{{PreviousMenuNext("Learn/JavaScript/Objects/Basics", "Learn/JavaScript/Objects/Object-oriented_JS", "Learn/JavaScript/Objects")}}

Revision Source

<div>{{draft}}{{LearnSidebar}}</div>

<div>{{PreviousMenuNext("Learn/JavaScript/Objects/Basics", "Learn/JavaScript/Objects/Object-oriented_JS", "Learn/JavaScript/Objects")}}</div>

<p class="summary">JavaScript Object Notation (JSON) is a standard format for representing structured data as JavaScript objects, which is commonly used for representing and transmitting data on web sites (i.e. sending some data from the server to the client, so it can be displayed on a web page). You'll come across it quite often, so in this article we give you all you need to work with JSON using JavaScript, including accessing data items in a JSON object and writing your own JSON.</p>

<table class="learn-box standard-table">
 <tbody>
  <tr>
   <th scope="row">Prerequisites:</th>
   <td>Basic computer literacy, a basic understanding of HTML and CSS, familiarity with JavaScript basics (see <a href="/en-US/docs/Learn/JavaScript/First_steps">First steps</a> and <a href="/en-US/docs/Learn/JavaScript/Building_blocks">Building blocks</a>) and OOJS basics (see <a href="/en-US/docs/Learn/JavaScript/Object-oriented/Introduction">Introduction to objects</a>).</td>
  </tr>
  <tr>
   <th scope="row">Objective:</th>
   <td>To understand how to work with data stored in JSON, and create your own JSON objects.</td>
  </tr>
 </tbody>
</table>

<h2 id="No_really_what_is_JSON">No, really, what is JSON?</h2>

<p>{{glossary("JSON")}} is a data format following JavaScript object syntax, which was popularized by <a href="https://en.wikipedia.org/wiki/Douglas_Crockford">Douglas Crockford</a>. Even though it is based on JavaScript syntax, it can be used independently from JavaScript, and many programming environments feature the ability to read (parse) and generate JSON.</p>

<p>JSON can exist as an object, or a string — the former is used when you want to read data out of the JSON, and the latter is used when you want to send the JSON across the network. This is not a big issue —&nbsp; JavaScript provides a global <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON">JSON</a> object that has methods available for converting between the two.</p>

<p>A JSON object can be stored in its own file, which is basically just a text file with an extension of <code>.json</code>, and a {{glossary("MIME type")}} of <code>application/json</code>.</p>

<h3>JSON structure</h3>

<p>We've implied above that a JSON object is basically a JavaScript object, and this is mostly right. You can include the same basic data types inside JSON as you can in a standard JavaScript object — strings, numbers, arrays, booleans, and other object literals. This allows you to construct a data hierarchy, like so:</p>

<pre class="brush: json">
{
&nbsp; "squadName" : "Super hero squad",
&nbsp; "homeTown" : "Metro City",
&nbsp; "formed" : 2016,
&nbsp; "secretBase" : "Super tower",
  "active" : true,
&nbsp; "members" : [
&nbsp;&nbsp;&nbsp; {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "name" : "Molecule Man",
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "age" : 29,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "secretIdentity" : "Dan Jukes",
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "powers" : [
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "Radiation resistance",
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "Turning tiny",
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "Radiation blast"
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ]
&nbsp;&nbsp;&nbsp; },
&nbsp;&nbsp;&nbsp; {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "name" : "Madame Uppercut",
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "age" : 39,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "secretIdentity" : "Jane Wilson",
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "powers" : [
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "Million tonne punch",
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "Damage resistance",
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "Superhuman reflexes"
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ]
&nbsp;&nbsp;&nbsp; },
&nbsp;&nbsp;&nbsp; {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "name" : "Eternal Flame",
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "age" : 1000000,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "secretIdentity" : "Unknown",
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "powers" : [
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "Immortality",
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "Heat Immunity",
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "Inferno",
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "Teleportation",
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "Interdimensional travel"
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ]
&nbsp;&nbsp;&nbsp; }
&nbsp; ]
}</pre>

<p>If we loaded this object into a JavaScript program, saved in a variable called <code>superHeroes</code> for example, we could then access the data inside it using the same dot/bracket notation we looked at in the last article. For example:</p>

<pre class="brush: js">
superHeroes.hometown
superHeroes["active"]</pre>

<p>To access data further down the hierarchy, you simply have to chain the required property names and array indexes together.&nbsp; For example, to access the third superpower of the second hero listed in the members list, you'd do this:</p>

<pre class="brush: js">
superHeroes["members"][1]["powers"][2]</pre>

<ol>
 <li>First we have the variable name — <code>superHeroes</code>.</li>
 <li>Inside that we want to access the <code>members</code> property, so we use <code>["members"]</code>.</li>
 <li><code>members</code> contains an array populated by objects. We want to access the second object inside the array, so we use <code>[1]</code>.</li>
 <li>Inside this object, we want to access the <code>powers</code> property, so we use <code>["powers"]</code>.</li>
 <li>Inside the <code>powers</code> property is an array containing the selected hero's superpowers. We want the third one, so we use <code>[2]</code>.</li>
</ol>

<div class="note">
<p><strong>Note</strong>: We've made the JSON seen above available inside a variable in our JSONText.html example (see source code). Try loading this up and then accessing data inside the variable via your browser's JavaScript console.</p>
</div>

<h3>Arrays as JSON</h3>

<p>Above we said "We've implied above that a JSON object is basically a JavaScript object, and this is mostly right" — the reason we said "mostly right" is because an array can also be a valid JSON object, for example:</p>

<pre>
[
  {
    "name" : "Molecule Man",
    "age" : 29,
    "secretIdentity" : "Dan Jukes",
    "powers" : [
      "Radiation resistance",
      "Turning tiny",
      "Radiation blast"
    ]
  },
  {
&nbsp;&nbsp;&nbsp; "name" : "Madame Uppercut",
&nbsp;&nbsp;&nbsp; "age" : 39,
&nbsp;&nbsp;&nbsp; "secretIdentity" : "Jane Wilson",
&nbsp;&nbsp;&nbsp; "powers" : [
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "Million tonne punch",
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "Damage resistance",
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "Superhuman reflexes"
&nbsp;&nbsp;&nbsp; ]
&nbsp; }
]</pre>

<p>The above is perfectly valid JSON. You'd just have to access array items by starting with an array index, for example <code>[0]["powers"][0]</code>.</p>

<h3>Other notes</h3>

<ul>
 <li>JSON is purely a data format — it contains only properties, no methods.</li>
 <li>JSON requires double quotes to be used to be valid. It is safest to write it with double quotes, not single quotes.</li>
 <li>Even a single misplaced comma or colon can cause a JSON file to go wrong, and not work. You should be careful to validate any data you are attempting to use (although computer-generated JSON is less likely to include errors, as long as the generator program is working correctly). You can validate JSON using an application like <a href="https://jsonlint.com/">JSONLint</a>.</li>
 <li>JSON can actually take the form of any data type that is valid for inclusion inside a standard JSON object, not just arrays or objects. So for example, a single string or number would be a valid JSON object. Not that this would be particularly useful...</li>
</ul>

<h2>Active learning: Working through a JSON example</h2>

<p>&nbsp;</p>

<ol>
</ol>

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

<p>In this article, we've given you a simple guide to using JSON in your programs, including how to create and parse JSON, and how to access data locked inside it. In the next article we'll begin looking at object oriented JavaScript.</p>

<p>{{PreviousMenuNext("Learn/JavaScript/Objects/Basics", "Learn/JavaScript/Objects/Object-oriented_JS", "Learn/JavaScript/Objects")}}</p>
Revert to this revision