JS JSON Parsing

JSON is an acronym that stands for JavaScript Object Notation. It is an extremely lightweight data-interchange format for data exchange that can occur between server and client, and it is quick and easy to parse and generate.

JSON just like XML, is also a text-based format that's simple to write and easy to understand for both humans and computers, however, JSON’s data structures occupy less bandwidth than their XML versions. 

JSON is based on two primary structures:

  • Object: It is defined as an unordered collection of key/value pairs (i.e key: value). Every single object begins with a left curly bracket ‘{‘ and ends with a right curly bracket’}’. Here, multiple key/value pairs are separated by a comma ‘,’.
  • Array: The array structure is defined as an ordered list of values. It begins with a left bracket ‘[‘and ends with a right bracket ‘]’. Values are separated by a comma ‘,’.

In JSON, property names or keys are taken as strings, whereas the value can be a stringnumbertrue or falsenull, or even an object or an array

Note: Strings must always be enclosed in double quotes ("…”) and it can accommodate escape characters such as n, t, and so on. The JSON object may look like this:

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

While an example of a JSON array may look like this:

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

Tip: A data-interchange format is a text format used to interchange or exchange data between different platforms, as well as operating systems. The most popular and lightweight data-interchange format for web applications is JSON.

 

Parsing JSON Data in JavaScript

JSON data received from the web server can be easily parsed in JavaScript by the use of the JSON.parse() method. This method parses a JSON string and subsequently constructs the JavaScript value or object described by the string. when the given string is not valid JSON, a syntax error will return.

Take for instance we've received the following JSON-encoded string from a web server:

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

So, we can simply use JSON.parse() method to convert this JSON string into a JavaScript object and access individual values using the dot notation (.), as shown in the example below:

// Store JSON data in a JS variable
var json = '{"name": "Peter", "age": 22, "country": "United States"}';

// Converting JSON-encoded string to JS object
var obj = JSON.parse(json);

// Accessing individual value from JS object
alert(obj.name); // Outputs: Peter
alert(obj.age); // Outputs: 22
alert(obj.country); // Outputs: United States

To better understand this, check out the tutorial on PHP JSON parsing, and learn how to return JSON data from a web server in response, and how to encode/decode JSON data on the server side using PHP.

 

Parsing Nested JSON Data in JavaScript

Like some other objects, JSON objects and arrays can also be nested. However, JSON objects can arbitrarily contain other JSON objects, arrays, nested arrays, arrays of JSON objects, etc. 

The example here will show you how to parse a nested JSON object and 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 object
var obj = JSON.parse(json);

// Define recursive function to print nested values
function 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 object
printValues(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

In some cases, JavaScript object or value from your code needs to be transferred to the server during Ajax communication. Basically, JavaScript provides JSON.stringify() method for this purpose as it converts a JavaScript value to a JSON string. This is shown below:

 

Stringify a JavaScript Object

The examples below review to you how to convert a JavaScript object to a JSON string:

// Sample JS object
var obj = {"name": "Peter", "age": 22, "country": "United States"};

// Converting JS object to JSON string
var json = JSON.stringify(obj);
alert(json);

The output of the example above will look like this:

Note: JavaScript and JSON objects look quite similar, however, they are not the same. For instance, in JavaScript, object property names can be enclosed in single quotes ('...') or double quotes ("..."), or the quote can even be omitted altogether. whereas, in JSON, all property names must at all times be enclosed in double quotes.

 

Stringify a JavaScript Array

Also, you can convert the JavaScript arrays to JSON strings, as shown below:

// Sample JS array
var arr = ["Apple", "Banana", "Mango", "Orange", "Papaya"];

// Converting JS array to JSON string
var json = JSON.stringify(arr);
alert(json);

The output of the example above will look like this:

Warning: Don’t you ever use the eval() function to evaluate JSON data, including function definitions in JSON string and converting them back into executable functions with the eval() method. This is because it allows an attacker to inject malicious JavaScript code into your application.