- 3 years ago
- Zaid Bin Khalid
- 134507 Views
-
15
In this session, you will learn how to encode and decode JSON data in JavaScript with the help of an example.
What is JSON
JavaScript Object Notation also knew as JSON. Between server and client relationship JSON is used which is an extremely lightweight data-interchange format for data exchange and easy to parse and quick to generate. JSON is easy to write and understand for both humans and computers which is based on a text format.
Types of JSON
JSON depend upon two basic structures:
{
"book": {
"name": "Harry Potter and the Goblet of Fire",
"author": "J. K. Rowling",
"year": 2000,
"genre": "Fantasy Fiction",
"bestseller": true
}
}
Parsing JSON Data in JavaScript
In JavaScript, by using JSON.parse( ) method you can easily data received from the webserver. In JSON string if the given string is not valid, the result you will get is a syntax error. As shown in the example:
{"name": "Peter", "age": 22, "country": "United States"}
By using the JSON.parse( ) method in JavaScript to convert the string into a JavaScript Object and access individual values by using the do notation (.), as shown in the example:
// 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
Parsing Nested JSON Data in JavaScript
You can also nested JSON objects and arrays. In JavaScript, JSON objects can contain other JSON objects, nested arrays, arrays, arrays of the JSON object, and so on. In mention below example, you will learn how to extract all the values and parse a nested JSON 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
During an Ajax communication JavaScript object or value from your code sometime need to be transferred to the server. JavaScript provides a method that converts a JavaScript value to a JSON String by using JSON. stringify ( ) as shown in the example:
Stringify a JavaScript Object
Mention below example will show how to convert a JavaScript object to 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 result of above example will show as:
{"name":"Peter","age":22,"country":"United States"}
Stringify a JavaScript Array
Mention below example will show how to convert a JavaScript array to JSON strings:
// 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 result of above example will show as:
["Apple","Banana","Mango","Orange","Papaya"]
- 3 years ago
- Zaid Bin Khalid
- 134507 Views
-
15