• Skip to main content
  • Select language
  • Skip to search
MDN Web Docs
  • Technologies
    • HTML
    • CSS
    • JavaScript
    • Graphics
    • HTTP
    • APIs / DOM
    • WebExtensions
    • MathML
  • References & Guides
    • Learn web development
    • Tutorials
    • References
    • Developer Guides
    • Accessibility
    • Game development
    • ...more docs
Learn web development
  1. MDN
  2. Learn web development
  3. JavaScript
  4. Introducing JavaScript objects
  5. Working with JSON data

Working with JSON data

In This Article
  1. No, really, what is JSON?
    1. JSON structure
    2. Arrays as JSON
    3. Other notes
  2. Active learning: Working through a JSON example
    1. Getting started
    2. Loading our JSON
    3. Populating the header
    4. Creating the hero information cards
  3. Converting between objects and text
  4. Summary
  5. See also
Previous Overview: Objects Next

 

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?

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 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 JavaScript object basics 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 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 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 that 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...
  • Unlike in JavaScript code in which identifiers may be used as properties, in JSON, only strings may be used as properties.

Active learning: Working through a JSON example

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

Getting started

To begin with, make local copies of our heroes.html and style.css files. The latter contains some simple CSS to style our page, while the former contains some very simple body HTML:

<header>
</header>
<section>
</section>

Plus a <script> element to contain the JavaScript code we will be writing in this exercise. At the moment it only contains two lines, which grab references to the <header> and <section> elements and store them in variables:

var header = document.querySelector('header');
var section = document.querySelector('section');

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 it into our page, and use some nifty DOM manipulation to display it, like this:

Loading our JSON

To load our JSON into our page, we are going to use an API called XMLHttpRequest (often called XHR). This is a very useful JavaScript object that allows us to make network requests to retrieve resources from a server via JavaScript (e.g. images, text, JSON, even HTML snippets), meaning that we can update small sections of content without having to reload the entire page. This has led to more responsive web pages, and sounds exciting, but it is unfortunately beyond the scope of this article to teach it in much more detail.

  1. To start with, we are going to store the URL of the JSON file we want to retrieve in a variable. Add the following at the bottom of your JavaScript code:
    var requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
  2. To create a request, we need to create a new request object instance from the XMLHttpRequest constructor, using the new keyword. Add the following below your last line:
    var request = new XMLHttpRequest();
  3. Now we need to open a new request using the open() method. Add the following line:
    request.open('GET', requestURL);

    This takes at least two parameters — there are other optional parameters available. We only need the two mandatory ones for this simple example:

    • The HTTP method to use when making the network request. In this case GET is fine, as we are just retrieving some simple data.
    • The URL to make the request to — this is the URL of the JSON file that we stored earlier.
  4. Next, add the following two lines — here we are setting the responseType to JSON, so the server will know we want a JSON object returned, and sending the request with the send() method:
    request.responseType = 'json';
    request.send();
  5. The last bit of this section involves waiting for the response to return from the server, then dealing with it. Add the following code below your previous code:
    request.onload = function() {
      var superHeroes = request.response;
      populateHeader(superHeroes);
      showHeroes(superHeroes);
    }

Here we are storing the response to our request (available in the response property) in a variable called superHeroes; this variable will now contain our JSON! We are then passing that JSON to two function calls — the first one will fill the <header> with the correct data, while the second one will create an information card for each hero on the team, and insert it into the <section>.

We have wrapped the code in an event handler that runs when the load event fires on the request object (see onload) — this is because the load event fires when the response has successfully returned; doing it this way guarantees that request.response will definitely be available when we come to try to do something with it.

Populating the header

Now we've retrieved our JSON data, let's make use of it by writing the two functions we referenced above. First of all, add the following function definition below the previous code:

function populateHeader(jsonObj) {
  var myH1 = document.createElement('h1');
  myH1.textContent = jsonObj['squadName'];
  header.appendChild(myH1);
  var myPara = document.createElement('p');
  myPara.textContent = 'Hometown: ' + jsonObj['homeTown'] + ' // Formed: ' + jsonObj['formed'];
  header.appendChild(myPara);
}

We have called the parameter jsonObj, so that's what we need to call the JSON object inside it. Here we first create an <h1> element with createElement(), set its textContent to equal the squadName property of the JSON, then append it to the header using appendChild(). We then do a very similar operation with a paragraph: create it, set its text content and append it to the header. The only difference is that its text is set to a concatenated string containing both the homeTown and formed properties of the JSON.

Creating the hero information cards

Next, add the following function at the bottom of the code, which creates and displays the superhero cards:

function showHeroes(jsonObj) {
  var heroes = jsonObj['members'];
  for (var i = 0; i < heroes.length; i++) {
    var myArticle = document.createElement('article');
    var myH2 = document.createElement('h2');
    var myPara1 = document.createElement('p');
    var myPara2 = document.createElement('p');
    var myPara3 = document.createElement('p');
    var myList = document.createElement('ul');
    myH2.textContent = heroes[i].name;
    myPara1.textContent = 'Secret identity: ' + heroes[i].secretIdentity;
    myPara2.textContent = 'Age: ' + heroes[i].age;
    myPara3.textContent = 'Superpowers:';
    var superPowers = heroes[i].powers;
    for (var j = 0; j < superPowers.length; j++) {
      var listItem = document.createElement('li');
      listItem.textContent = superPowers[j];
      myList.appendChild(listItem);
    }
    myArticle.appendChild(myH2);
    myArticle.appendChild(myPara1);
    myArticle.appendChild(myPara2);
    myArticle.appendChild(myPara3);
    myArticle.appendChild(myList);
    section.appendChild(myArticle);
  }
}

To start with, we store the members property of the JSON in a new variable. This array contains multiple objects that contain the information for each hero.

Next, we use a for loop to loop through each object in the array. For each one, we:

  1. Create several new elements: an <article>, an <h2>, three <p>s, and a <ul>.
  2. Set the <h2> to contain the current hero's name.
  3. Fill the three paragraphs with their secretIdentity, age, and a line saying "Superpowers:" to introduce the information in the list.
  4. Store the powers property in another new variable called superPowers — this contains an array that lists the current hero's superpowers.
  5. Use another for loop to loop through the current hero's superpowers — for each one we create a <li> element, put the superpower inside it, then put the listItem inside the <ul> element (myList) using appendChild().
  6. The very last thing we do is to append the <h2>, <p>s, and <ul> inside the <article> (myArticle), then append the <article> inside the <section>. The order in which things are appended is important, as this is the order they will be displayed inside the HTML.

Note: If you are having trouble getting the example to work, try referring to our heroes-finished.html source code (see it running live also.)

Note: If you are having trouble following the dot/bracket notation we are using to access the JSON, it can help to have the superheroes.json file open in another tab or your text editor, and refer to it as you look at our JavaScript. You should also refer back to our JavaScript object basics article for more information on dot and bracket notation.

Converting between objects and text

The above example was simple in terms of accessing the JSON, because we set the XHR to return the response already in JSON format, using:

request.responseType = 'json';

But sometimes we aren't so lucky — sometimes we'll receive some JSON data formatted as a text string, and we'll want to convert it to an object. And when we want to send JSON data as some kind of message, we'll often need to convert it to a string for it to work correctly. Luckily, these two problems are so common in web development that a built-in JSON object was added to browsers quite a while ago, containing the following two methods:

  • parse(): Accepts a JSON object in text string form as a parameter, and returns the corresponding object.
  • stringify(): Accepts a JSON object as a parameter, and returns the equivalent text string form.

You can see the first one in action in our heroes-finished-json-parse.html example (see the source code) — this does exactly the same thing as the example we built up earlier, except that we set the XHR to return the JSON as text, then used parse() to convert it to an actual JSON object. The key snippet of code is here:

request.open('GET', requestURL);
request.responseType = 'text'; // now we're getting a string!
request.send();
request.onload = function() {
  var superHeroesText = request.response; // get the string from the response
  var superHeroes = JSON.parse(superHeroesText); // convert it to an object
  populateHeader(superHeroes);
  showHeroes(superHeroes);
}

As you might guess, stringify() works the opposite way. Try entering the following lines into your browser's JavaScript console one by one to see it in action:

var myJSON = { "name": "Chris", "age": "38" };
myJSON
var myString = JSON.stringify(myJSON);
myString

Here we're creating a JSON object, then checking what it contains, then converting it to a string using stringify() — saving the return value in a new variable — then checking it again.

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.

See also

  • JSON object reference page
  • XMLHttpRequest object reference page
  • Using XMLHttpRequest
  • HTTP request methods
  • Official JSON web site with link to ECMA standard

Previous Overview: Objects Next

 

Document Tags and Contributors

Tags: 
  • Article
  • Beginner
  • CodingScripting
  • Guide
  • JavaScript
  • JSON
  • l10n:priority
  • Learn
  • Objects
  • Tutorial
 Contributors to this page: qdirks, systematis, chrisdavidmills, nmve, Jeremie, fscholz
 Last updated by: qdirks, Jul 7, 2017, 7:50:34 AM
See also
  1. Complete beginners start here!
  2. Getting started with the Web
    1. Getting started with the Web overview
    2. Installing basic software
    3. What will your website look like?
    4. Dealing with files
    5. HTML basics
    6. CSS basics
    7. JavaScript basics
    8. Publishing your website
    9. How the Web works
  3. HTML — Structuring the Web
  4. Introduction to HTML
    1. Introduction to HTML overview
    2. Getting started with HTML
    3. What's in the head? Metadata in HTML
    4. HTML text fundamentals
    5. Creating hyperlinks
    6. Advanced text formatting
    7. Document and website structure
    8. Debugging HTML
    9. Assessment: Marking up a letter
    10. Assessment: Structuring a page of content
  5. Multimedia and embedding
    1. Multimedia and embedding overview
    2. Images in HTML
    3. Video and audio content
    4. From object to iframe — other embedding technologies
    5. Adding vector graphics to the Web
    6. Responsive images
    7. Assessment: Mozilla splash page
  6. HTML tables
    1. HTML tables overview
    2. HTML table basics
    3. HTML Table advanced features and accessibility
    4. Assessment: Structuring planet data
  7. CSS — Styling the Web
  8. Introduction to CSS
    1. Introduction to CSS overview
    2. How CSS works
    3. CSS syntax
    4. Selectors introduction
    5. Simple selectors
    6. Attribute selectors
    7. Pseudo-classes and pseudo-elements
    8. Combinators and multiple selectors
    9. CSS values and units
    10. Cascade and inheritance
    11. The box model
    12. Debugging CSS
    13. Assessment: Fundamental CSS comprehension
  9. Styling text
    1. Styling text overview
    2. Fundamental text and font styling
    3. Styling lists
    4. Styling links
    5. Web fonts
    6. Assessment: Typesetting a community school homepage
  10. Styling boxes
    1. Styling boxes overview
    2. Box model recap
    3. Backgrounds
    4. Borders
    5. Styling tables
    6. Advanced box effects
    7. Assessment: Creating fancy letterheaded paper
    8. Assessment: A cool-looking box
  11. CSS layout
    1. CSS layout overview
    2. Introduction
    3. Floats
    4. Positioning
    5. Practical positioning examples
    6. Flexbox
    7. Grids
  12. JavaScript — Dynamic client-side scripting
  13. JavaScript first steps
    1. JavaScript first steps overview
    2. What is JavaScript?
    3. A first splash into JavaScript
    4. What went wrong? Troubleshooting JavaScript
    5. Storing the information you need — Variables
    6. Basic in JavaScript — Numbers and operators
    7. Handling text — Strings in JavaScript
    8. Useful string methods
    9. Arrays
    10. Assessment: Silly story generator
  14. JavaScript building blocks
    1. JavaScript building blocks overview
    2. Making decisions in your code — Conditionals
    3. Looping code
    4. Functions — Reusable blocks of code
    5. Build your own function
    6. Function return values
    7. Introduction to events
    8. Assessment: Image gallery
  15. Introducing JavaScript objects
    1. Introducing JavaScript objects overview
    2. Object basics
    3. Object-oriented JavaScript for beginners
    4. Object prototypes
    5. Inheritance in JavaScript
    6. Working with JSON data
    7. Object building practise
    8. Assessment: Adding features to our bouncing balls demo
  16. Accessibility — Make the web usable by everyone
  17. Accessibility guides
    1. Accessibility overview
    2. What is accessibility?
    3. HTML: A good basis for accessibility
    4. CSS and JavaScript accessibility best practices
    5. WAI-ARIA basics
    6. Accessible multimedia
    7. Mobile accessibility
  18. Accessibility assessment
    1. Assessment: Accessibility troubleshooting
  19. Tools and testing
  20. Cross browser testing
    1. Cross browser testing overview
    2. Introduction to cross browser testing
    3. Strategies for carrying out testing
    4. Handling common HTML and CSS problems
    5. Handling common JavaScript problems
    6. Handling common accessibility problems
    7. Implementing feature detection
    8. Introduction to automated testing
    9. Setting up your own test automation environment
  21. Server-side website programming
  22. First steps
    1. First steps overview
    2. Introduction to the server-side
    3. Client-Server overview
    4. Server-side web frameworks
    5. Website security
  23. Django web framework (Python)
    1. Django web framework (Python) overview
    2. Introduction
    3. Setting up a development environment
    4. Tutorial: The Local Library website
    5. Tutorial Part 2: Creating a skeleton website
    6. Tutorial Part 3: Using models
    7. Tutorial Part 4: Django admin site
    8. Tutorial Part 5: Creating our home page
    9. Tutorial Part 6: Generic list and detail views
    10. Tutorial Part 7: Sessions framework
    11. Tutorial Part 8: User authentication and permissions
    12. Tutorial Part 9: Working with forms
    13. Tutorial Part 10: Testing a Django web application
    14. Tutorial Part 11: Deploying Django to production
    15. Web application security
    16. Assessment: DIY mini blog
  24. Express Web Framework (node.js/JavaScript)
    1. Express Web Framework (Node.js/JavaScript) overview
    2. Express/Node introduction
    3. Setting up a Node (Express) development environment
    4. Express tutorial: The Local Library website
    5. Express Tutorial Part 2: Creating a skeleton website
    6. Express Tutorial Part 3: Using a database (with Mongoose)
    7. Express Tutorial Part 4: Routes and controllers
    8. Express Tutorial Part 5: Displaying library data
    9. Express Tutorial Part 6: Working with forms
    10. Express Tutorial Part 7: Deploying to production
  25. Further resources
  26. Advanced learning material
    1. WebGL: Graphics processing
  27. Common questions
    1. HTML questions
    2. CSS questions
    3. JavaScript questions
    4. How the Web works
    5. Tools and setup
    6. Design and accessibility
  28. How to contribute