26. JavaScript JSON

What you will learn

  • What JSON is and its rules
  • How to convert with JSON.stringify() and JSON.parse()
  • How to handle bad JSON
  • How JSON is used to store and send data

What is JSON?

JSON (JavaScript Object Notation) is a plain-text format for data. It looks like a JavaScript object, but it is just text, which makes it ideal for sending between a browser and a server, or for storing in a file.

JSON

{
  "name": "Sam",
  "age": 25,
  "student": true,
  "skills": ["HTML", "CSS"],
  "address": null
}

The rules of JSON

  • Property names must be in double quotes.
  • Strings use double quotes only. Single quotes are not allowed.
  • Allowed values: string, number, true, false, null, array, and object.
  • No comments, no trailing commas, and no undefined or functions.

Object to text: JSON.stringify

Example

<pre id="demo"></pre>

<script>
  const user = { name: "Sam", age: 25, skills: ["HTML", "CSS"] };

  const text = JSON.stringify(user);
  const pretty = JSON.stringify(user, null, 2);   // indented by 2 spaces

  document.getElementById("demo").textContent =
    "Compact:\n" + text + "\n\nPretty:\n" + pretty;
</script>

Output (after the script runs)

Compact:
{"name":"Sam","age":25,"skills":["HTML","CSS"]}

Pretty:
{
  "name": "Sam",
  "age": 25,
  "skills": [
    "HTML",
    "CSS"
  ]
}

Text to object: JSON.parse

Example

<p id="demo"></p>

<script>
  const text = '{"title":"JSON","order":26,"tags":["data","text"]}';
  const lesson = JSON.parse(text);

  document.getElementById("demo").textContent =
    lesson.title + " is lesson " + lesson.order + ", first tag: " + lesson.tags[0];
</script>

Output (after the script runs)

JSON is lesson 26, first tag: data

Always expect bad JSON

JSON.parse throws a SyntaxError if the text is not valid. Data from outside your code can always be wrong, so wrap it in try...catch.

Example

<p id="demo"></p>

<script>
  function safeParse(text) {
    try {
      return JSON.parse(text);
    } catch (error) {
      return null;
    }
  }

  const good = safeParse('{"ok": true}');
  const bad = safeParse("{'ok': true}");   // single quotes: invalid

  document.getElementById("demo").textContent =
    "good: " + JSON.stringify(good) + " | bad: " + bad;
</script>

Output (after the script runs)

good: {“ok”:true} | bad: null

What does not survive

When you stringify, some things are lost or changed:

  • Functions and undefined values are dropped.
  • A Date becomes a text string, and parsing does not turn it back into a date.
  • NaN and Infinity become null.

Example

<p id="demo"></p>

<script>
  const data = {
    name: "Sam",
    greet() { return "hi"; },
    missing: undefined,
    when: new Date(2026, 0, 15, 12, 0)
  };

  const copy = JSON.parse(JSON.stringify(data));
  document.getElementById("demo").textContent =
    "Keys kept: " + Object.keys(copy).join(", ") +
    " | when is a " + typeof copy.when;
</script>

Output (after the script runs)

Keys kept: name, when | when is a string

Using JSON with arrays of objects

Example

<ul id="demo"></ul>

<script>
  const json = `[
    { "title": "HTML", "lessons": 25 },
    { "title": "CSS", "lessons": 31 }
  ]`;

  const courses = JSON.parse(json);

  document.getElementById("demo").innerHTML = courses
    .map((c) => `<li>${c.title}: ${c.lessons} lessons</li>`)
    .join("");
</script>

Output (after the script runs)

  • HTML: 25 lessons
  • CSS: 31 lessons

Where JSON is used

  • Data sent between a browser and a server (you will use it with Fetch).
  • Settings and configuration files.
  • Saving data in the browser, which the Browser APIs lesson covers.

Security: never use eval() to read JSON. Always use JSON.parse(). If you then show values from outside sources in the page, use textContent, not innerHTML.

Common mistakes

  • Using single quotes or unquoted property names in JSON text.
  • Leaving a trailing comma.
  • Calling JSON.parse on an object that is already an object.
  • Expecting dates and functions to survive a round trip.
  • Not handling invalid JSON.

Exercise

Parse the JSON text and show Notebook: 13.50, calculated from the price and quantity.

Show solution
<p id="demo"></p>

<script>
  const text = '{"product":"Notebook","price":4.5,"qty":3}';
  const item = JSON.parse(text);
  const total = item.price * item.qty;

  document.getElementById("demo").textContent =
    item.product + ": " + total.toFixed(2);
</script>

Knowledge check

1. Which method turns an object into JSON text?

JSON.stringify()

2. Which quotes does JSON require around property names?

Double quotes.

3. What happens when JSON.parse gets invalid text?

It throws a SyntaxError, so use try...catch.

Summary

  • JSON is a text format for data with strict rules.
  • stringify makes text, and parse makes objects.
  • Always handle bad JSON, and never use eval().
Scroll to Top