Deserializing JSON means converting a JSON-formatted string into a JavaScript object or array. In JavaScript, the JSON.parse() method is used to perform this conversion.
[Approach 1]: Deserializing a JSON String into an Object
The JSON.parse() method converts a valid JSON string into a JavaScript object.
- Store the JSON-formatted data in a string.
- Pass the JSON string to JSON.parse().
- Access the properties of the resulting JavaScript object.
Syntax:
JSON.parse(text, reviver)Example : This example converts a JSON string containing user information into a JavaScript object.
// JSON string representing user data
const jsonString =
'{"name":"Alen","age":30,"city":"Wonderland"}';
// Convert the JSON string into a JavaScript object
const user = JSON.parse(jsonString);
// Access object properties
console.log("Name:", user.name);
console.log("Age:", user.age);
console.log("City:", user.city);
Output
Name: Alen Age: 30 City: Wonderland
[Approach 2]: Deserializing a JSON String into an Array of Objects
A JSON string can also contain an array of objects. After parsing the JSON string, array methods such as forEach() can be used to access each object.
- Store the JSON array as a string.
- Use JSON.parse() to convert it into a JavaScript array.
- Loop through the array to access the properties of each object.
Example: This example converts a JSON string containing multiple products into a JavaScript array of objects.
// JSON string representing product data
const productsJson = `[
{
"id": 1,
"name": "Laptop",
"price": 1200
},
{
"id": 2,
"name": "Smartphone",
"price": 500
}
]`;
// Convert the JSON string into a JavaScript array
const products = JSON.parse(productsJson);
// Access each product
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