How to parse JSON data with JavaScript

JSON stands for JavaScript Object Notation. JSON is a human-readable format of data transmitted between a server and a browser. JSON data is stored in key/value pair in a file saved with .json extension. Even though the syntax of JSON looks similar to JS, it doesn’t need JS or any other language.

JSON data exist in the form of strings that make it easy for us to parse it and convert it into a native JS object whenever we need to extract data from it.

Here is a simple example of a JSON object.

{
"name": "Coding Panel",
"niche": "Programming Tutorials & Articles",
"website_url": "www.condingpanel.com"
}

The JSON object can be saved in a variable.

let website = {
"name": "Coding Panel",
"niche": "Programming Tutorials & Articles",
"website_url": "www.condingpanel.com"
}

You can also write the JSON object as a string within a JS program or file. For example,

let website = ‘{ "name": "Coding Panel", "niche": "Programming Tutorials & Articles", "website_url": "www.condingpanel.com" }’

JSON objects look very similar to JS objects, but these are different as keys in JS objects are not strings.

For example, the following piece of code is JS object

let website = {
name : "Coding Panel",
niche : "Programming Tutorials & Articles",
website_url : "www.condingpanel.com"
}

As you see, there are no quotes around the keys (name, niche, or website_url).

Parsing JSON Data

In JS, dot notation is used to access the JSON data.

For example, to access the name of the website, we would use:

console.log (website.name);

JavaScript has two functions that can be used to parse JSON data. The JSON.stringify() method converts a JSON object into a JSON string, whereas, JSON.parse() function converts a JSON string into a JSON object.

Let’s understand these functions with a simple example.

<!DOCTYPE html>
<html>
   <body>
      <p id="movie"></p>
      <script>
         var movie = '{"movie_name": "WonderWoman 2", "release_date": "August 2020"}';
         var obj = JSON.parse(movie);
         
         document.getElementById("movie").innerHTML =
         "Name: " + obj.movie_name + "<br>" +
         "Release Date: " + obj.release_date;
      </script>
   </body>
</html>

 

Output:

I have tried to keep the tutorial as simple as possible. But still, if you have any questions, feel free to leave it in the comment section below.

Leave a Reply

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