Working with JSON - Learn web development | MDN 20.02.
26, 00:45
seria'ization.
A JSON string can be stored in its own fi)e, which is basica))y just a text fi)e with an extension of
.json , and a MBME type of application/json .
JSON structure
As described above, JSON is a string whose format very much resemb)es JavaScript object )itera)
format. The fo))owing is a va)id JSON string representing an object. Note that it is a)so a va)id
JavaScript object )itera) — just with some more syntax restrictions.
JSON
[Link] Page 2 of 13
Working with JSON - Learn web development | MDN 20.02.26, 00:45
{
"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"
]
}
]
}
Bf you )oad this JSON in your JavaScript program as a string, you can parse it into a norma) object
and then access the data inside it using the same dot/bracket notation we )ooked at in the
JavaScript object basics artic)e. For examp)e:
[Link] Page 3 of 13
Working with JSON - Learn web development | MDN 20.02.26, 00:45
JS
[Link];
[Link][1].powers[2];
WXY First, we have the variab)e name — superHeroes .
ZXY Bnside that, we want to access the members property, so we use .members .
[XY members contains an array popu)ated by objects. We want to access the second object
inside the array, so we use [1] .
\XY Bnside this object, we want to access the powers property, so we use .powers .
]XY Bnside the powers property is an array containing the se)ected hero's superpowers. We
want the third one, so we use [2] .
The key takeaway is that there's rea))y nothing specia) about working with JSON; after you've
parsed it into a JavaScript object, you work with it just )ike you wou)d with an object dec)ared
using the same object )itera) syntax.
Note: We've made the JSON seen above avai)ab)e inside a variab)e in our
[Link]) examp)e (see the source code ). Try )oading this up and then
accessing data inside the variab)e via your browser's JavaScript conso)e.
Arrays as JSON
Above we mentioned that JSON text basica))y )ooks )ike a JavaScript object inside a string. We
can a)so convert arrays to/from JSON. The be)ow examp)e is perfect)y va)id JSON:
JSON
[Link] Page 4 of 13
Working with JSON - Learn web development | MDN 20.02.26, 00:45
[
{
"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 examp)e
superHeroes[0].powers[0] .
The JSON can a)so contain a sing)e primitive. For examp)e, 29 , "Dan Jukes" , or true are a))
va)id JSON.
JSON syntax restrictions
As mentioned ear)ier, any JSON is a va)id JavaScript )itera) (object, array, number, etc.). The
converse is not true, though—not a)) JavaScript object )itera)s are va)id JSON.
JSON can on)y contain seria'izab'e data types. This means:
For primitives, JSON can contain string )itera)s, number )itera)s, true , false , and
null . Notab)y, it cannot contain undefined , NaN , or Infinity .
For non-primitives, JSON can contain object )itera)s 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 va)id JSON data types.
Strings must be enc)osed in doub)e quotes, not sing)e quotes.
Numbers must be written in decima) notation.
Each property of an object must be in the form of "key": value . Property names must
be string )itera)s enc)osed in doub)e quotes. Specia) JavaScript syntax, such as methods,
is not a))owed because methods are functions, and functions are not va)id JSON data
types.
[Link] Page 5 of 13
Working with JSON - Learn web development | MDN 20.02.26, 00:45
Objects and arrays cannot contain trai)ing commas.
Comments are not a))owed in JSON.
Even a sing)e misp)aced comma or co)on can make a JSON fi)e inva)id and cause it to fai). You
shou)d be carefu) to va)idate any data you are attempting to use (a)though computer-generated
JSON is )ess )ike)y to inc)ude errors, as )ong as the generator program is working correct)y). You
can va)idate JSON using an app)ication )ike JSONLint or JSON-va)idate
Note: Now you've read through this section, you might a)so want to supp)ement your
MDN 'earning partner
)earning with Scrimba's JSON review interactive tutoria), which
provides some usefu) guidance around basic JSON syntax and how to view JSON
request data inside your browser's devtoo)s.
Working through a JSON examp(e
So, )et's work through an examp)e to show how we cou)d make use of some JSON formatted data
on a website.
Getting started
To begin with, make )oca) copies of our [Link]) and sty)[Link] fi)es. The )atter contains
some simp)e CSS to sty)e our page, whi)e the former contains some very simp)e body HTML, p)us
a <script> e)ement to contain the JavaScript code we wi)) be writing in this exercise:
HTML
<header>
...
</header>
<section>
...
</section>
<script>
// JavaScript goes here
</script>
We have made our JSON data avai)ab)e on our GitHub, at [Link]
area/javascript/oojs/json/[Link] .
[Link] Page 6 of 13
Working with JSON - Learn web development | MDN 20.02.26, 00:45
We are going to )oad the JSON into our script, and use some nifty DOM manipu)ation to disp)ay it,
)ike this:
Top-9eve9 function
The top-)eve) function )ooks )ike this:
JS
async function populate() {
const requestURL =
"[Link]
area/javascript/oojs/json/[Link]";
const request = new Request(requestURL);
const response = await fetch(request);
const superHeroes = await [Link]();
populateHeader(superHeroes);
populateHeroes(superHeroes);
}
[Link] Page 7 of 13
Working with JSON - Learn web development | MDN 20.02.26, 00:45
To obtain the JSON, we use an APB ca))ed Fetch. This APB a))ows 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 sma)) sections of content without having to re)oad the entire page.
Bn our function, the first four )ines use the Fetch APB to fetch the JSON from the server:
we dec)are the requestURL variab)e to store the GitHub URL
we use the URL to initia)ize a new Request object.
we make the network request using the fetch() function, and this returns a Response
object
we retrieve the response as JSON using the json() function of the Response object.
Note: The fetch() APB is asynchronous. You can )earn about asynchronous functions
in detai) in our Asynchronous JavaScript modu)e, but for now, we')) just say that we need
to add the keyword async before the name of the function that uses the fetch APB, and
add the keyword await before the ca))s to any asynchronous functions.
After a)) that, the superHeroes variab)e wi)) contain the JavaScript object based on the JSON.
We are then passing that object to two function ca))s — the first one fi))s the <header> with the
correct data, whi)e the second one creates an information card for each hero on the team, and
inserts it into the <section> .
Popu9ating the header
Now that we've retrieved the JSON data and converted it into a JavaScript object, )et's make use
of it by writing the two functions we referenced above. First of a)), add the fo))owing function
definition be)ow the previous code:
JS
function populateHeader(obj) {
const header = [Link]("header");
const myH1 = [Link]("h1");
[Link] = [Link];
[Link](myH1);
const myPara = [Link]("p");
[Link] = `Hometown: ${[Link]} // Formed: ${[Link]}`;
[Link](myPara);
}
Here we first create an h1 e)ement with createElement() , set its textContent to equa) the
[Link] Page 8 of 13
Working with JSON - Learn web development | MDN 20.02.26, 00:45
squadName property of the object, then append it to the header using appendChild() . We then
do a very simi)ar operation with a paragraph: create it, set its text content and append it to the
header. The on)y difference is that its text is set to a temp)ate )itera) containing both the
homeTown and formed properties of the object.
Creating the hero information cards
Next, add the fo))owing function at the bottom of the code, which creates and disp)ays the
superhero cards:
JS
[Link] Page 9 of 13
Working with JSON - Learn web development | MDN 20.02.26, 00:45
function populateHeroes(obj) {
const section = [Link]("section");
const heroes = [Link];
for (const hero of heroes) {
const myArticle = [Link]("article");
const myH2 = [Link]("h2");
const myPara1 = [Link]("p");
const myPara2 = [Link]("p");
const myPara3 = [Link]("p");
const myList = [Link]("ul");
[Link] = [Link];
[Link] = `Secret identity: ${[Link]}`;
[Link] = `Age: ${[Link]}`;
[Link] = "Superpowers:";
const superPowers = [Link];
for (const power of superPowers) {
const listItem = [Link]("li");
[Link] = power;
[Link](listItem);
}
[Link](myH2);
[Link](myPara1);
[Link](myPara2);
[Link](myPara3);
[Link](myList);
[Link](myArticle);
}
}
To start with, we store the members property of the JavaScript object in a new variab)e. This
array contains mu)tip)e objects that contain the information for each hero.
Next, we use a for...of )oop to iterate through each object in the array. For each one, we:
WXY Create severa) new e)ements: an <article> , an <h2> , three <p> s, and a <ul> .
ZXY Set the <h2> to contain the current hero's name .
[XY Fi)) the three paragraphs with their secretIdentity , age , and a )ine saying
"Superpowers:" to introduce the information in the )ist.
[Link] Page 10 of 13
Working with JSON - Learn web development | MDN 20.02.26, 00:45
\XY Store the powers property in another new constant ca))ed superPowers — this contains
an array that )ists the current hero's superpowers.
]XY Use another for...of )oop to )oop through the current hero's superpowers — for each
one we create an <li> e)ement, put the superpower inside it, then put the listItem
inside the <ul> e)ement ( myList ) using appendChild() .
cXY The very )ast 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 wi)) be disp)ayed inside the
HTML.
Note: Bf you are having troub)e getting the examp)e to work, try referring to our heroes-
[Link]) source code (see it running )ive a)so.)
Note: Bf you are having troub)e fo))owing the dot/bracket notation we are using to access
the JavaScript object, it can he)p to have the [Link] fi)e open in another tab
or your text editor, and refer to it as you )ook at our JavaScript. You shou)d a)so refer
back to our JavaScript object basics artic)e for more information on dot and bracket
notation.
Ca99ing the top-9eve9 function
Fina))y, we need to ca)) our top-)eve) populate() function:
JS
populate();
Converting between objects and text
The above examp)e was simp)e in terms of accessing the JavaScript object, because we
converted the network response direct)y into a JavaScript object using [Link]() .
But sometimes we aren't so )ucky — sometimes we receive a raw JSON string, and we need to
convert it to an object ourse)ves. And when we want to send a JavaScript object across the
network, we need to convert it to JSON (a string) before sending it. Lucki)y, these two prob)ems
are so common in web deve)opment that a bui)t-in JSON object is avai)ab)e in browsers, which
contains the fo))owing two methods:
parse() : Accepts a JSON string as a parameter, and returns the corresponding
[Link] Page 11 of 13
Working with JSON - Learn web development | MDN 20.02.26, 00:45
JavaScript object.
stringify() : Accepts an object as a parameter, and returns the equiva)ent JSON string.
You can see the first one in action in our [Link]) examp)e (see the
source code ) — this does exact)y the same thing as the examp)e we bui)t up ear)ier, except
that:
we retrieve the response as text rather than JSON, by ca))ing the text() method of the
response
we then use parse() to convert the text to a JavaScript object.
The key snippet of code is here:
JS
async function populate() {
const requestURL =
"[Link]
area/javascript/oojs/json/[Link]";
const request = new Request(requestURL);
const response = await fetch(request);
const superHeroesText = await [Link]();
const superHeroes = [Link](superHeroesText);
populateHeader(superHeroes);
populateHeroes(superHeroes);
}
As you might guess, stringify() works the opposite way. Try entering the fo))owing )ines into
your browser's JavaScript conso)e one by one to see it in action:
JS
let myObj = { name: "Chris", age: 38 };
myObj;
let myString = [Link](myObj);
myString;
Here we're creating a JavaScript object, checking what it contains, converting it to a JSON string
using stringify() — saving the return va)ue in a new variab)e — then checking it again.
[Link] Page 12 of 13
Working with JSON - Learn web development | MDN 20.02.26, 00:45
Summary
Bn this )esson, we've introduced you to using JSON in your programs, inc)uding how to create and
parse JSON, and how to access data )ocked inside it. Bn the next artic)e, we')) give you some tests
that you can use to check how we)) you've understood and retained a)) this information.
See a(so
JSON reference
Fetch APB overview
Using Fetch
HTTP request methods
Previous Overview: Dynamic scripting with JavaScript Next
Your b)ueprint for a better internet.
[Link] Page 13 of 13