How to use JSON with JavaScript

Here's an example of using JavaScript to output JSON data to a web page.

JSON is based on a subset of JavaScript, and a JSON document can easily be converted into a JavaScript value.

Here's a simple example of how you can use JavaScript to store a JSON text, then output it to a web page.

Basic Example

Here's the JSON data we'll use in this example:

We'll use JavaScript to take the above JSON data, format it with HTML tags, and output it to the HTML document.

Here's the code:

Try it

In this example, we output the formatted JSON data using innerHTML.

We also place the JavaScript inside a function, then call that function once the page loads (using window.onload. Alternatively, you could use some other event to call the function.

Nested For Loop

Here's another example. This time we'll use a larger JSON file with deeper nesting.

Not only does this file have artist information, but each artist has a number of albums. So we'll need to loop through the artists, and also loop through each artists' albums.

Try it

Just like in the first example, this example uses a function that is called when the page loads.

However, the function in the second example uses two for loops — one nested inside the other — to retrieve the nested data.