Deserializing a JSON into a JavaScript object
Deserializing a JSON into a JavaScript object refers to the process of converting a JSON (JavaScript Object Notation) formatted string into a native JavaScript object. This allows developers to work with the data in JavaScript by accessing its properties and methods directly.
JavaScript Object Notation exchanges 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 parses the JSONString into a JavaScript object, allowing access to its properties just like any other JavaScript object.
// 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);
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 converts the productsJson string into a JavaScript array of objects, allowing iteration with forEach() to access and display product details.
// 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 an array of objects
let products = JSON.parse(productsJson);
// Looping through the array to access each product's properties
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