Deserializing a JSON into a JavaScript object
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.
Javascript
let jsonString = '{"name": "Alice", "age": 30, "city": "Wonderland"}' ;
let user = JSON.parse(jsonString);
console.log( "Name:" , user.name);
console.log( "Age:" , user.age);
console.log( "City:" , user.city);
|
Output
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.
Javascript
let productsJson =
'[{"id": 1, "name": "Laptop","price": 1200},{"id": 2,"name": "Smartphone","price": 500}]' ;
let products = JSON.parse(productsJson);
products.forEach(product => {
console.log(`Product ID: ${product.id},
Name: ${product.name}, Price: $${product.price}`);
});
|
Output
Product ID: 1,
Name: Laptop, Price: $1200
Product ID: 2,
Name: Smartphone, Price: $500
Last Updated :
08 Jan, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...