JSON and data
Store and share data as JSON, and parse it safely with try/catch.
- Explain what JSON is and when it is used
- Convert between objects and JSON with stringify and parse
- Read values from nested objects and arrays
- Handle invalid JSON with try/catch
In plain English
JSON (JavaScript Object Notation) is a text format for storing and sharing data, built from objects, arrays, strings, numbers, booleans and null. JSON.stringify turns a JavaScript value into a JSON string, and JSON.parse turns a JSON string back into a value. A JSON value can nest objects inside arrays and arrays inside objects to represent rich data. When a string is not valid JSON, JSON.parse throws an error, so you wrap it in a try/catch block to fail gracefully instead of crashing.
Step by step
- 1Create a JavaScript object with a nested object and an array.
- 2Turn it into a string with JSON.stringify.
- 3Turn the string back into an object with JSON.parse.
- 4Wrap a JSON.parse call in try/catch and confirm a bad string is caught.
const profile = {
name: "Amina",
age: 28,
hobbies: ["reading", "cycling"],
address: { city: "Cairo", country: "Egypt" }
};
const text = JSON.stringify(profile);
console.log(text);
const restored = JSON.parse(text);
console.log(restored.address.city);
try {
JSON.parse("this is not json");
} catch (err) {
console.log("Invalid JSON caught");
}Common mistakes
- Forgetting that JSON keys must be double-quoted strings, unlike JavaScript object literals.
- Calling JSON.parse on a string that is not JSON and getting an uncaught error.
- Confusing a JSON string with the object it represents and forgetting to parse it first.
- Trying to put functions or comments inside JSON, which the format does not allow.
Parse a nested payload
Write a function readCity(jsonText) that parses the string and returns the city from inside the address object. Return "Unknown" if parsing fails.
function readCity(jsonText) {
}What does JSON.stringify do?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.