Aral Code

Arrays & Objects Lesson 21 of 30

JavaScript JSON — Saving and Sharing Data

JSON is the standard text format for data on the web. Learn its rules, convert objects to text with JSON.stringify and back with JSON.parse.

When apps send data to each other, such as a weather app asking a server for the forecast, they need a common format. Today that format is almost always JSON (JavaScript Object Notation). It looks just like JavaScript objects and arrays, written as text.

What JSON looks like

{
  "school": "Mabini National High School",
  "students": 1240,
  "hasSHS": true,
  "strands": ["STEM", "ABM", "HUMSS", "TVL-ICT"],
  "principal": { "name": "Dr. Santos", "since": 2021 }
}

JSON rules

JSON is stricter than JavaScript:

  • Property names must be in double quotes: "name", not name.
  • Strings must use double quotes. Single quotes are not allowed.
  • Allowed values: strings, numbers, true, false, null, arrays and objects.
  • No functions, no undefined, no comments, and no trailing commas.

Object to JSON text: JSON.stringify

Example JSON.stringify
<pre id="out"></pre>
<script>
  const order = {
    customer: "Aling Nena",
    items: ["pandesal", "kape"],
    total: 33,
    paid: true,
  };
  const text = JSON.stringify(order);
  const pretty = JSON.stringify(order, null, 2);
  document.getElementById("out").textContent =
    "Compact:\n" + text + "\n\nPretty:\n" + pretty;
</script>

The third argument (2) adds indentation so humans can read it. Without it, everything is on one line, which is smaller for sending over the internet.

JSON text to object: JSON.parse

Example JSON.parse
<pre id="out"></pre>
<script>
  const text = '{"name":"Juan","grades":[88,91,85]}';
  const data = JSON.parse(text);
  const avg = data.grades.reduce((a, b) => a + b, 0) / data.grades.length;
  document.getElementById("out").textContent =
    `${data.name}'s average is ${avg.toFixed(2)}`;
</script>

After parsing, data is a normal object. You can use dot notation, loops and array methods on it.

Handling bad JSON

If the text isn't valid JSON, JSON.parse throws an error that stops your script. Wrap it in try...catch to handle it gracefully:

Example Catching invalid JSON
<p id="out"></p>
<script>
  const bad = "{'name': 'Juan',}";
  try {
    JSON.parse(bad);
  } catch (err) {
    document.getElementById("out").textContent = "Invalid JSON: " + err.message;
  }
</script>

Where JSON is used

  • APIs: servers send data like weather, news or prices as JSON.
  • Saving in the browser: localStorage can only store text, so you stringify objects before saving and parse them when loading.
  • Config files: many tools, like package.json in Node.js projects, use JSON.

Saving an object with localStorage

const settings = { theme: "dark", fontSize: 18 };

// Save
localStorage.setItem("settings", JSON.stringify(settings));

// Load (later, even after closing the browser)
const saved = JSON.parse(localStorage.getItem("settings"));
console.log(saved.theme);   // "dark"

Getting JSON from a server

You'll often see fetch used together with JSON:

const response = await fetch("https://example.com/api/products.json");
const products = await response.json();   // parses the JSON for you

The await keyword waits for the internet to respond. Working with servers is an advanced topic, but now you know what the data looks like when it arrives.

Quick Quiz

Check what you learned. Walang grade ito, practice lang. 🙂

1. Which is valid JSON?
2. What does JSON.stringify({a: 1}) return?
3. Which function turns JSON text back into an object?
4. Why use JSON with localStorage?

By Sir Reyel · Last updated 2026-12-04