Javascript Fetch JSON Data (Simple Examples)

Welcome to a tutorial on how to fetch JSON data in Javascript. So you are working on a project that needs to get some data from the server? But just how do we deal with this “JSON data”?

To get JSON data in Javascript, simply fetch and parse the data as JSON:

  • fetch("URL")
  • .then(res => res.json())
  • .then(data => { DO SOMETHING });

That covers the quick basics, but read on for detailed examples!

 

 

TLDR – QUICK SLIDES

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

 

JAVASCRIPT FETCH JSON DATA

All right, let us now get into the examples of fetching JSON data from the server.

 

1) FETCH JSON ARRAY

1A) DUMMY JSON DATA

1a-array.json
["Red","Green","Blue"]
  • For those who have lazily skipped the basics – “JSON data” is just a string.
  • Remember how we define an array in Javascript? var colors = ["Red", "Green", "Blue"];
  • Looks familiar? JSON – Javascript Object Notion. Get it?

 

1B) FETCH JSON ARRAY

1b-array.html
// (A) FETCH DATA FROM SERVER
fetch("1a-array.json")
 
// (B) RETURN DATA AS JSON
.then(res => res.json())
.then(data => {
  console.log(data);
  for (let value of data) { console.log(value); }
})
 
// (C) OPTIONAL
.catch(err => console.error(err))
.finally(() => console.log("Done!"));

This is the same introduction snippet, a couple more details here:

  • fetch(URL) Self-explanatory, fetch data from this URL.
  • then(res => res.json()) Return the server response as JSON. That is, parse the JSON data back into an array or object.
  • then(data => { DO SOMETHING }) Do something with the results.
  • .catch(err => console.error(err)) Optional, handle any errors.
  • .finally(() => console.log("Done!")); Optional, run this at the end. Regardless of success or errors.

Yep, fetch() pretty much works like a try-catch-finally block.

P.S. If you do not know what those () => {} and PARAM => {} are, it’s called an “arrow function”. A quick explanation is in the extras section below.

 

 

2) FETCH JSON OBJECT

2A) DUMMY JSON DATA

2a-object.json
{"name":"Jon","email":"jon@doe.com"}

For those who still cannot see this as “Javascript” – var person = { name : "Jon", email : "jon@doe.com" };

 

2B) FETCH JSON OBJECT

2b-object.html
// (A) FETCH DATA FROM SERVER
fetch("2a-object.json")
 
// (B) RETURN DATA AS JSON
.then(res => res.json())
.then(data => {
  console.log(data);
  for (let [key, value] of Object.entries(data)) {
    console.log(key, value);
  }
})

// (C) OPTIONAL
.catch(err => console.error(err))
.finally(() => console.log("Done!"));

Not much difference here. The same old parse as JSON data, and work with the results.

 

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

EXTRA BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

EXTRA) ARROW FUNCTIONS

  • You already know this – function twice (n) { return n * 2; }
  • We can also do this – var twice = function (n) { return n * 2; };
  • Arrow function shorthand – var twice = (n) => { return n * 2; };
  • If there is only one parameter, we can omit the round brackets – var twice = n => { return n * 2; };
  • If the function only has one statement, we can omit the curly brackets and even return – var twice = n => n * 2;

 

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

Javascript Fetch JSON Data (click to enlarge)

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *