What is JSON?
Before we look at how to deal with JSON, let’s take a second to understand what it is (and what it isn’t).
There are two ways data can be stored in JSON:
- a collection of name/value pairs (aka a JSON object)
- an ordered list of values (aka a JSON array)
When receiving data from a web server, the data is always a string, which means that it’s your job to convert it into a data structure you can work with.
If you’d like to find out more about how JSON works, please visit the JSON website.
Fetching JSON from a Remote API
In the following examples, we’ll use the fantastic icanhazdadjoke API. As you can read in its documentation, making a GET request where the
Accept header is set to
application/json will see the API return a JSON payload.
Let’s start with a simple example:
const xhr = new XMLHttpRequest(); xhr.onreadystatechange = () => if (xhr.readyState === XMLHttpRequest.DONE) console.log(typeof xhr.responseText); console.log(xhr.responseText); ; xhr.open('GET', 'https://icanhazdadjoke.com/', true); xhr.setRequestHeader('Accept', 'application/json'); xhr.send(null); // string // "id":"daaUfibh","joke":"Why was the big cat disqualified from the race? Because it was a cheetah.","status":200
if (xhr.readyState === XMLHttpRequest.DONE) const res = JSON.parse(xhr.responseText); console.log(res); ; // Object id: "fiyPR7wPZDd", joke: "When does a joke become a dad joke? When it becomes apparent.", status: 200
A for…in loop iterates over all enumerable properties of an object:
const res = JSON.parse(xhr.responseText); for (const key in res) if(obj.hasOwnProperty(key)) console.log(`$key : $res[key]`) // id : H6Elb2LBdxc // joke : What's blue and not very heavy? Light blue. // status : 200
Please be aware that
for...of loops will iterate over the entire prototype chain, so here we’re using
hasOwnProperty to ensure that the property belongs to our