JavaScript JSON

The text format for sending and saving data, with stringify and parse.

Lesson 42 of 56Intermediate12 min read

JSON (JavaScript Object Notation) is a text format for data. It looks almost exactly like JavaScript objects and arrays, which is a big part of why it became the standard way for programs to exchange data on the web. APIs send JSON, apps save settings as JSON, and many configuration files are JSON.

Because JSON is plain text, any programming language can read and write it, not only JavaScript. A server written in Python can send JSON that your JavaScript reads, and the other way round. Learning JSON is the step that lets your pages work with data from the outside world.

What JSON looks like

JSON
{
  "name": "Pixel",
  "age": 2,
  "vaccinated": true,
  "toys": ["ball", "rope"],
  "owner": null
}

Data like this can be nested as deeply as you need: objects inside arrays inside objects. Most API responses are larger versions of exactly this structure.

JSON's strict syntax rules

  • Keys must be wrapped in double quotes, as in "name".
  • Strings use double quotes only.
  • Allowed values are strings, numbers, true and false, null, arrays and objects.
  • Not allowed: functions, undefined, comments, trailing commas and single quotes.

These rules are stricter than JavaScript's, which is the most common source of "invalid JSON" errors. A single trailing comma or a single quote is enough to make the whole text unreadable.

Converting between JSON and JavaScript

MethodConverts
JSON.stringify(value)a JavaScript value into a JSON string
JSON.parse(text)a JSON string into a JavaScript value

JSON.stringify(obj, null, 2) adds line breaks and two-space indentation, which makes the output much easier to read while debugging.

JSON.stringify quietly leaves out properties whose values are functions or undefined, because JSON can't represent them.

Parsing JSON safely

JSON.parse throws an error if the text isn't valid JSON. When the text comes from somewhere you don't control, such as a file, browser storage or a server, wrap the call in try...catch (see Errors) and fall back to a sensible default.

JSON Syntax

JSON methods

const text = JSON.stringify({ a: 1 });       // '{"a":1}'
const obj = JSON.parse('{"a":1}');           // { a: 1 }
const pretty = JSON.stringify(obj, null, 2);  // indented

JSON Summary

  • JSON is a text format for data that looks like JavaScript objects and arrays.
  • Keys and strings must use double quotes; comments and trailing commas aren't allowed.
  • JSON.stringify turns a value into a JSON string; JSON.parse turns it back.
  • Functions and undefined are dropped by JSON.stringify.
  • Wrap JSON.parse in try...catch when the text comes from outside your code.

JSON Examples

Each example runs in the page. Edit the code and press Run to see what changes.

Example 1

Stringify and parse

const order = {
  id: 1042,
  items: ["Latte", "Muffin"],
  paid: true,
  note: undefined,
  print() { return "hi"; },
};

const json = JSON.stringify(order);
console.log(json);
console.log(typeof json);

const back = JSON.parse(json);
console.log(back.items[1], typeof back);

console.log(JSON.stringify(order, null, 2));
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Lines 1 to 7A normal JavaScript object, including undefined and a method.
  2. Line 9Turn it into a JSON string. note and print are dropped because JSON can't store them.
  3. Line 13Turn the string back into an object.
  4. Line 16Pretty-printed with 2-space indentation.
Example 2

Reading API-style data

This string is exactly the kind of text a weather API might send.

const response = '{"city":"Oslo","temp":-3,"forecast":[{"day":"Mon","sky":"snow"},{"day":"Tue","sky":"sun"}]}';

const weather = JSON.parse(response);

console.log(`${weather.city}: ${weather.temp}°C`);
weather.forecast.forEach(f => console.log(`${f.day} → ${f.sky}`));
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 1Raw JSON text.
  2. Line 3Parse it into an object we can use.
  3. Lines 5 to 6Now it's normal JavaScript data.
Example 3

Handling invalid JSON

const inputs = ['{"ok":true}', "{ok: true}", "{'ok': true}", ""];

for (const text of inputs) {
  try {
    const data = JSON.parse(text);
    console.log("✅ Parsed:", data);
  } catch (error) {
    console.log("❌ Invalid JSON:", JSON.stringify(text));
  }
}
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 1One valid JSON string, three invalid ones (unquoted key, single quotes, empty).
  2. Lines 4 to 9try…catch stops one bad input from crashing everything.

Common JSON Mistakes

Using single quotes or unquoted keys

Don't
{ name: 'Sam' }
Do
{ "name": "Sam" }

That's valid JavaScript, but not valid JSON.

Parsing something that's already an object

Don't
const user = { name: "Sam" };
JSON.parse(user); // SyntaxError: "[object Object]" is not valid JSON
Do
const user = JSON.parse('{"name":"Sam"}');

JSON.parse takes a string. If you already have an object, you don't need it.

Trailing commas

Don't
{ "a": 1, "b": 2, }
Do
{ "a": 1, "b": 2 }

JSON in Real Projects

JSON is the web's data language

When a weather app, a social feed or a game leaderboard loads data, it's almost always JSON. package.json describes JavaScript projects, VS Code settings are JSON, and localStorage uses JSON to save objects. Next up: loading JSON from real APIs with fetch.

JSON Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Turn the object into JSON, then back again.

const text = JSON.({ score: 10 });
const data = JSON.(text);
Multiple choiceeasy

Which is valid JSON?

Predict the outputmedium

What does this print?

console.log(JSON.stringify({ a: 1, b: undefined, c: null }));
Fix the bugmedium

The code should parse the saved settings and log Theme: dark. Fix it.

const saved = "{'theme': 'dark', 'size': 16,}";
const settings = JSON.parse(saved);
console.log("Theme:", settings.theme);
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • Logs "Theme: dark"
  • No errors

JSON Quiz

3 questions to check what you learned.

  1. What does JSON stand for?

    • Java Standard Object Notation
    • JavaScript Object Notation
    • JavaScript Online Network
    • JSON Simple Object Name
  2. What type does JSON.stringify([1, 2]) return?

    • array
    • object
    • string
    • number
  3. Can JSON contain functions?

    • Yes
    • No
    • Only arrow functions
    • Only in arrays

JSON Challenge

Safe JSON loader

Write a function safeParse(text, fallback) that:

  1. Returns the parsed value if text is valid JSON
  2. Returns fallback if parsing fails (use try…catch)

So safeParse('[1,2]', []) → [1, 2] and safeParse("oops", []) → [].

function safeParse(text, fallback) {
  // your code
}

console.log(safeParse('[1,2]', []));
console.log(safeParse("oops", []));
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • Parses valid JSON
  • Returns the fallback for invalid JSON
  • Handles an empty string
  • Uses try…catch