How to Parse JSON data in JavaScript

FusionReactor 8.7.7 Released
Parse Variable Patterns using Regex

Assuming that you’ve used a web app before, there is a strong possibility that it uses JSON format to create a framework, store and transmit data between its servers and connected devices. JavaScript Object Notation, which is popularly known as JSON is a useful data format, similar to a text file.

In this article, we’ll briefly go over how we can encode and decode JSON data in JavaScript. But firsts, let’s take a look at a few differences between JSON and JavaScript.

Introducing JSON

JSON is a lightweight data format for data exchange between devices and servers, which is easy to parse and generate. While there are a few similarities between JSON and JavaScript due to the JavaScript Syntax inspiration, JSON is a text-based format which is based on two main structures;

  • Object: We can define JSON objects as an unordered collection of values/Key pairs (i.e. key:value). You can find a left curly bracket { starting the object like this and ends with a right curly bracket } which are separated by a comma.
  • Array: unlike their counterparts, arrays are ordered list of values, which begins with a straight left bracket and ends with a suitable bracket. Commas separate both arrays and Objects.

A closer look at JSON objects, we realize that the key pairs are always in strings, while the value pair are either a string, number, boolean, or even an object or an array. However, strings must be enclosed in double quotes. It can contain escape characters such as \n, \t and \. , which may look this way:

{
"book": {
"name": "Harry Potter and the Goblet of Fire",
"author": "J. K. Rowling",
"year": 2000,
"genre": "Fantasy Fiction",
"bestseller": true
}}

A JSON array would look like this:

{
"fruits": [
"Apple",
"Banana",
"Strawberry",
"Mango"
]}

Parsing JSON Data in JavaScript

There are a few ways you can parse data in JavaScript. With the JSON.parse() method, you can quickly parse JSON data transmitted from the webserver. The JSON.parse method parses a JSON string and then constructs a script value described by the string. Also, all invalid JSON strings get a syntax error result.

For example, let’s assume the following JSON-encoded string was transmitted from our web server:

{"name": "Peter", "age": 22, "country": "United States"}

We can apply the JavaScript JSON.parse() method to convert this JSON string into a JavaScript object and use the dot notation (.) to access individual values. It should look like this:

// Store JSON data in a JS variablevar json = '{"name": "Peter", "age": 22, "country": "United States"}';
// Converting JSON-encoded string to JS objectvar obj = JSON.parse(json);
// Accessing individual value from JS objectalert(obj.name); // Outputs: Peteralert(obj.age); // Outputs: 22alert(obj.country); // Outputs: United States

Parsing Nested JSON Data in JavaScript

Nesting is another possibility of what can be done with a JSON object and array. Since a JSON object contains other JSON objects, arrays, nested arrays, etc., let’s use the following scenario to parse a nested JSON object and then extract all the values in JavaScript.

/* Storing multi-line JSON string in a JS variable
using the new ES6 template literals */var json = `{
"book": {
"name": "Harry Potter and the Goblet of Fire",
"author": "J. K. Rowling",
"year": 2000,
"characters": ["Harry Potter", "Hermione Granger", "Ron Weasley"],
"genre": "Fantasy Fiction",
"price": {
"paperback": "$10.40", "hardcover": "$20.32", "kindle": "$4.11"
}
}
}`;
// Converting JSON object to JS objectvar obj = JSON.parse(json);
// Define recursive function to print nested valuesfunction printValues(obj) {
for(var k in obj) {
if(obj[k] instanceof Object) {
printValues(obj[k]);
} else {
document.write(obj[k] + "<br>");
};
}};
// Printing all the values from the resulting objectprintValues(obj);
document.write("<hr>");
// Printing a single value
document.write(obj["book"]["author"] + "<br>"); // Prints: J. K. Rowling
document.write(obj["book"]["characters"][0] + "<br>"); // Prints: Harry Potter
document.write(obj["book"]["price"]["hardcover"]); // Prints: $20.32

Encoding Data as JSON in JavaScript

If you are familiar with the workflow of Ajax communication, then you will understand that sometimes you can transfer javaScript objects from your code to your server. However, JavaScript provides a specific string JSON.stringify() method to process this communication, which converts a JSON string as it is shown below:

Stringify a JavaScript Object

We’ll use the following scenario to convert a JavaScript object to JSON strong:

// Sample JS objectvar obj = {"name": "Peter", "age": 22, "country": "United States"};
// Converting JS object to JSON stringvar json = JSON.stringify(obj);alert(json);

The result should look like this:

{“name”:”Peter”,”age”:22,”country”:”United States”}

Stringify a JavaScript Array

This is easy to do. Let’s use the following example to convert a JavaScript array to JSON strings:

// Sample JS arrayvar arr = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
// Converting JS array to JSON stringvar json = JSON.stringify(arr);alert(json);

The result should look like this:

[“Apple”,”Banana”,”Mango”,”Orange”,”Papaya”]

How to Parse JSON data in JavaScript

We’ve successfully covered everything you need to know about how to encode and decode JSON data in JavaScript. Now get out there and parse or stringify JSON as you like.

Menu