JavaScript Foundations·The beginner gaps

JSON and data

Store and share data as JSON, and parse it safely with try/catch.

Beginner 11 min read Lesson 6 of 480 Challenge included
What you will be able to do
  • 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

  1. 1Create a JavaScript object with a nested object and an array.
  2. 2Turn it into a string with JSON.stringify.
  3. 3Turn the string back into an object with JSON.parse.
  4. 4Wrap a JSON.parse call in try/catch and confirm a bad string is caught.
json.jsJavaScript
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.
Your turn

Parse a nested payload

Medium

Write a function readCity(jsonText) that parses the string and returns the city from inside the address object. Return "Unknown" if parsing fails.

JAVASCRIPT · starter
function readCity(jsonText) {
}
Check your understanding before moving on.
Knowledge checkQuestion 1

What does JSON.stringify do?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Dates and numbers
Lesson 6 of 480 · 0% of course