JS JSON Parsing

What is JSON

JSON stands for JavaScript Object Notation. It is a lightweight data-interchange format used for fast and easy data exchange between server and client applications.

Similar to XML, JSON is a text-based format that is both human-readable and machine-readable. However, JSON data structures are more compact than their XML equivalents, making them more efficient in terms of bandwidth usage. JSON is built on two main structures:

  • Object: An unordered collection of key/value pairs. Objects are enclosed in curly braces {} and key/value pairs are separated by commas ,.
  • Array: An ordered list of values. Arrays are enclosed in square brackets [] and values are separated by commas ,.

In JSON, keys are always strings enclosed in double quotes ", while values can be strings, numbers, boolean values (true or false), null, objects, or arrays. Strings can include escape characters like \n, \t, and \\. Here is an example of a JSON object:

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

Here's an example of a JSON array:

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

 

Tip: A data-interchange format refers to a text format used for exchanging data across various platforms and operating systems. JSON stands out as the most popular and lightweight choice for data exchange in web applications.


Parsing JSON Data in JavaScript

In JavaScript, you can effortlessly parse JSON data fetched from a web server using the JSON.parse() method. This function interprets a JSON string and constructs the corresponding JavaScript value or object. If the provided string isn't valid JSON, it triggers a syntax error.

For example, assume we've received the following JSON-encoded string from a web server:

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

Now, you can use the JavaScript JSON.parse() method to convert this JSON string into a JavaScript object. After parsing, you can access individual values using dot notation (.), as shown 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

Please explore the tutorial on PHP JSON parsing to understand how to retrieve JSON data from a web server and encode/decode JSON data on the server side using PHP.


Parsing Nested JSON Data in JavaScript

JSON objects and arrays can be nested, containing other JSON objects, arrays, nested arrays, arrays of JSON objects, and so on. The example below demonstrates how to parse a nested JSON object and extract all its values using 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

Sometimes, data from your JavaScript code needs to be transferred to the server during an Ajax communication. JavaScript provides the JSON.stringify() method for this purpose, which converts a JavaScript value to a JSON string, as demonstrated below:

Stringify a JavaScript Object

The following example illustrates 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 above example will resemble the following JSON string:

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

Note: While JavaScript and JSON objects share similarities, they are not identical. In JavaScript, object property names can be enclosed in single quotes ('...') or double quotes ("..."), or sometimes omitted entirely. However, in JSON, all property names must be enclosed in double quotes.

Convert a JavaScript Array to JSON String

You can convert JavaScript arrays to JSON strings using the JSON.stringify() method, like this:

// 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 above example will look something like this:

["Apple","Banana","Mango","Orange","Papaya"]

 

Warning: Avoid using the eval() function to evaluate JSON data, especially when it includes function definitions. Using eval() can potentially allow attackers to inject malicious JavaScript code into your application.