To Deserialize a JSON into a JavaScript object, here we will use a common method JSON.parse() method.
JavaScript Object Notation is used to exchange data to or from a web server or RESTFull API. The data received from a web server is always a string. To use that data you need to parse the data with JSON.parse() which will return a JavaScript Object or Array of Objects.
Syntax:
JSON.parse( string, function );
Example 1: In this example, the JSON.parse()
method is used to parse the JSON string jsonString
into a JavaScript object (user
). The resulting user
object can then be accessed like any other JavaScript object, allowing you to retrieve the values of its properties.
// JSON string representing user data let jsonString = '{"name": "Alice", "age": 30, "city": "Wonderland"}' ;
// Deserializing the JSON string into a JavaScript object let user = JSON.parse(jsonString); // Accessing properties of the JavaScript object console.log( "Name:" , user.name); // Output: Alice
console.log( "Age:" , user.age); // Output: 30
console.log( "City:" , user.city); // Output: Wonderland
|
Name: Alice Age: 30 City: Wonderland
Example 2: In this example, the JSON.parse()
method is used to convert the productsJson
string, representing an array of products, into a JavaScript array of objects (products
). The resulting array can be iterated over using methods like forEach()
to access and display information about each product.
// JSON string representing a list of products let productsJson = '[{"id": 1, "name": "Laptop","price": 1200},{"id": 2,"name": "Smartphone","price": 500}]' ;
// Deserializing the JSON string into // a JavaScript array of objects let products = JSON.parse(productsJson); // Accessing properties of the JavaScript // objects in the array products.forEach(product => { console.log(`Product ID: ${product.id},
Name: ${product.name}, Price: $${product.price}`);
}); |
Product ID: 1, Name: Laptop, Price: $1200 Product ID: 2, Name: Smartphone, Price: $500