Parsing and Stringifying JSON
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. In this chapter, we’ll explore the powerful methods JSON.parse()
and JSON.stringify()
to work with JSON in JavaScript. We’ll also cover practical examples, use cases, and provide exercises to solidify your understanding.
8.1 Using JSON.parse()
to Convert JSON to JavaScript Objects
Explanation
The JSON.parse()
method is used to convert a JSON string into a JavaScript object. This is particularly useful when working with data fetched from APIs or local storage, which is often in JSON format.
Syntax
JSON.parse(text, reviver);
text
: A valid JSON string.reviver
(optional): A function that transforms the resulting object.
Example
const jsonString = '{"name": "Alice", "age": 25, "isStudent": false}';
const user = JSON.parse(jsonString);
console.log(user.name); // Output: Alice
console.log(user.age); // Output: 25
Using a Reviver Function
const jsonString = '{"birthYear": 2000}';
const user = JSON.parse(jsonString, (key, value) => {
if (key === "birthYear") {
return 2025 - value; // Calculate age
}
return value;
});
console.log(user.birthYear); // Output: 25
8.2 Using JSON.stringify()
to Convert JavaScript Objects to JSON
Explanation
The JSON.stringify()
method converts a JavaScript object or value to a JSON string. This is helpful for storing data in local storage, sending data to a server, or logging for debugging purposes.
Syntax
JSON.stringify(value, replacer, space);
value
: The object or value to convert.replacer
(optional): A function or array to filter properties.space
(optional): Adds indentation for readability.
Example
const user = { name: "Alice", age: 25, isStudent: false };
const jsonString = JSON.stringify(user);
console.log(jsonString); // Output: {"name":"Alice","age":25,"isStudent":false}
Adding Indentation
const prettyJson = JSON.stringify(user, null, 2);
console.log(prettyJson);
/*
{
"name": "Alice",
"age": 25,
"isStudent": false
}
*/
Filtering Properties with replacer
const filteredJson = JSON.stringify(user, ["name", "age"], 2);
console.log(filteredJson);
/*
{
"name": "Alice",
"age": 25
}
*/
8.3 Practical Examples and Use Cases
Fetching Data from an API
fetch("https://api.example.com/user")
.then((response) => response.json())
.then((data) => {
console.log(data);
});
Storing and Retrieving Data in Local Storage
const settings = { theme: "dark", fontSize: 16 };
localStorage.setItem("settings", JSON.stringify(settings));
const retrievedSettings = JSON.parse(localStorage.getItem("settings"));
console.log(retrievedSettings.theme); // Output: dark
Exercises
1. Parse a JSON String
Convert the following JSON string into a JavaScript object and access the city
property:
const jsonString = '{"name": "John", "age": 30, "address": {"city": "New York", "zip": "10001"}}';
2. Stringify a JavaScript Object
Convert the following object into a JSON string with 4 spaces of indentation:
const product = { id: 1, name: "Laptop", price: 899.99 };
3. Use a Reviver Function
Write a reviver function to transform all numeric values in the following JSON string by multiplying them by 10:
const jsonString = '{"score": 5, "level": 2}';
Multiple-Choice Quiz Questions
1. What does JSON.parse()
do?
- A. Converts a JavaScript object to a JSON string.
- B. Converts a JSON string to a JavaScript object.
- C. Saves a JSON string to local storage.
- D. Sends a JSON string to a server.
Answer: B
Explanation: JSON.parse()
converts a valid JSON string into a JavaScript object.
2. What is the purpose of the replacer
parameter in JSON.stringify()
?
- A. To filter or transform properties during stringification.
- B. To add indentation for readability.
- C. To specify a default value for missing properties.
- D. To parse JSON strings into objects.
Answer: A
Explanation: The replacer
parameter allows filtering or transforming properties when converting objects to JSON strings.
3. Which method can you use to convert a JavaScript object to a JSON string?
- A.
JSON.parse()
- B.
JSON.stringify()
- C.
toString()
- D.
JSON.encode()
Answer: B
Explanation: JSON.stringify()
converts a JavaScript object or value into a JSON string.
Answers to Exercises
1. Parse a JSON String
const jsonString = '{"name": "John", "age": 30, "address": {"city": "New York", "zip": "10001"}}';
const user = JSON.parse(jsonString);
console.log(user.address.city); // Output: New York
2. Stringify a JavaScript Object
const product = { id: 1, name: "Laptop", price: 899.99 };
const jsonString = JSON.stringify(product, null, 4);
console.log(jsonString);
3. Use a Reviver Function
const jsonString = '{"score": 5, "level": 2}';
const transformed = JSON.parse(jsonString, (key, value) =>
typeof value === "number" ? value * 10 : value
);
console.log(transformed); // Output: { score: 50, level: 20 }