Working with JSON

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa). You'll come across it quite often, so in this article, we give you all you need to work with JSON using JavaScript, including parsing JSON so you can access data within it, and creating JSON.

Prerequisites: An understanding of HTML and the fundamentals of CSS, familiarity with JavaScript basics as covered in previous lessons.
Learning outcomes:
  • What JSON is — a very commonly used data format based on JavaScript object syntax.
  • That JSON can also contain arrays.
  • Retrieve JSON as a JavaScript object using mechanisms available in Web APIs (for example, Response.json() in the Fetch API).
  • Access values inside JSON data using bracket and dot syntax.
  • Converting between objects and text using JSON.parse() and JSON.stringify().

No, really, what is JSON?

JSON is a text-based data format following JavaScript object syntax. It represents structured data as a string, which is useful when you want to transmit data across a network. Even though it closely resembles JavaScript object literal syntax, it can be used independently from JavaScript. Many programming environments feature the ability to read (parse) and generate JSON. In JavaScript, the methods for parsing and generating JSON are provided by the JSON object.

Note: Converting a string to a native object is called deserialization, while converting a native object to a string so it can be transmitted across the network is called serialization.

A JSON string can be stored in its own file, which is basically just a text file with an extension of .json, and a MIME type of application/json.

JSON structure

As described above, JSON is a string whose format very much resembles JavaScript object literal format. The following is a valid JSON string representing an object. Note how it is also a valid JavaScript object literal — just with some more syntax restrictions.

json
{
  "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 you load this JSON in your JavaScript program as a string, you can parse it into a normal object and then access the data inside it using the same dot/bracket notation we looked at in the JavaScript object basics article. For example:

js
superHeroes.homeTown;
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].

The key takeaway is that there's really nothing special about working with JSON; after you've parsed it into a JavaScript object, you work with it just like you would with an object declared using the same object literal syntax.

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

Arrays as JSON

Above we mentioned that JSON text basically looks like a JavaScript object inside a string. We can also convert arrays to/from JSON. The below example is perfectly valid JSON:

json
[
  {
    "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"
    ]
  }
]

You have to access array items (in its parsed version) by starting with an array index, for example superHeroes[0].powers[0].

The JSON can also contain a single primitive. For example, 29, "Dan Jukes", or true are all valid JSON.

JSON syntax restrictions

As mentioned earlier, any JSON is a valid JavaScript literal (object, array, number, etc.). The converse is not true, though—not all JavaScript object literals are valid JSON.

  • JSON can only contain serializable data types. This means:
    • For primitives, JSON can contain string literals, number literals, true, false, and null. Notably, it cannot contain undefined, NaN, or Infinity.
    • For non-primitives, JSON can contain object literals and arrays, but not functions or any other object types, such as Date, Set, and Map. The objects and arrays inside JSON need to further contain valid JSON data types.
  • Strings must be enclosed in double quotes, not single quotes.
  • Numbers must be written in decimal notation.
  • Each property of an object must be in the form of "key": value. Property names must be string literals enclosed in double quotes. Special JavaScript syntax, such as methods, is not allowed because methods are functions, and functions are not valid JSON data types.
  • Objects and arrays cannot contain trailing commas.
  • Comments are not allowed in JSON.

Even a single misplaced comma or colon can make a JSON file invalid and cause it to fail. 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 or JSON-validate

Note: Now you've read through this section, you might also want to supplement your learning with Scrimba's JSON review MDN learning partner interactive tutorial, which provide some useful guidance around basic JSON syntax and how to view JSON request data inside your browser's devtools.

Active learning: Working through a JSON example

So, let's work through an example to show how we could make use of some JSON formatted data on a website.

Getting started

We have made our JSON data available on our GitHub, at https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json.

We are going to load the JSON into our script, and use some nifty DOM manipulation to display it, like this:

Image of a document titled