How do you parse a json string in Javascript?

Published April 24, 2021

JSON - Java Script Object Notation is a light weight data format to transfer the data between server and client. Like XML JSON is also a text based data format. In this post we will cover what is parsing in JSON  and how to parse JSON in javascript with example.

JSON Parsing is data in the string format with specified fields, this string is in the form of JSON which has some specialized mechanism to arrange the data. This JSON has 2 structures

JSON Object which is an unordered key, value pair data, which is starts with an open curly bracket '{' and end with close curly bracket '}'

JSON Array which is an ordered list of values, it may contains list of JSON objects, strings... This array begins with an left bracket '[' and end with right bracket ']'

 

Simple JSON Object

{ "option_1": "Macrograph", "option_2": "Nanographia", "option_3": "Mycographia", "option_4": "Micrographia" }

 

Simple JSON Array

[

{ "option_1": "Macrograph", "option_2": "Nanographia", "option_3": "Mycographia", "option_4": "Micrographia" },

{ "option_1": "Macrograph", "option_2": "Nanographia", "option_3": "Mycographia", "option_4": "Micrographia" },

{ "option_1": "Macrograph", "option_2": "Nanographia", "option_3": "Mycographia", "option_4": "Micrographia" }

  ]

 

How to parse JSON in Javascript?

In Javascript we can easily parse the JSON string received from server by using JSON.parse() method. This method parse the given string into Javascript Object. If the given string is not a proper JSON format then it will return error.

 

Simple JSON String parser example

<!DOCTYPE html>
<html >
<head><meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
</head>
<script>
let jsonStr='{"explanation": "Robert Hooke published his observations related to the discovery of  cell in his scientific book called Micrographia.", "option_right": 4, "option_selected": -1, "options": [ { "option_1": "Macrograph", "option_2": "Nanographia", "option_3": "Mycographia", "option_4": "Micrographia" }  ], "question": "Robert Hooke published his observations in a book called _______.", "question_id": 1, "status": 0, "subject_id": 3 }';

let jsonObj=JSON.parse(jsonStr);
console.log(jsonObj);        
</script>
</html>

 

 

When we run the above example in the console it will print the JSON Object value

 

Javascript JSON Parser

 

We can remove/delete an existing property from JSON

<script>
let jsonStr='{ "options": [ { "option_1": "Macrograph", "option_2": "Nanographia", "option_3": "Mycographia", "option_4": "Micrographia" }  ]}';

let jsonObj=JSON.parse(jsonStr, (key, value) => {
    if(key == "option_2") return undefined;
    return value;
})
console.log(jsonObj);        
</script>

 

It will remove the option_2

output:

what is json parsing

 

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

942 Views