Leet School

{module 6}

JSON: data as text

How programs talk to each other20 min read

What you will be able to do

  • Read and write JSON, and say which rule a piece of broken JSON breaks.
  • Turn JSON text into a value with JSON.parse, and a value into JSON text with JSON.stringify.
  • Read a value deep inside nested data, such as the weight of the first bag in a delivery.

Why it matters

Highlands Coffee Growers is a coffee cooperative in Goroka, Papua New Guinea. Every Friday, Grace Yamo, its secretary, sends the buyer in the city a file that lists each farmer's bags. The buyer's program reads the file and pays each farmer.

One Friday, Grace typed a farmer's name by hand and left out one quotation mark. The buyer's program refused the whole file. Nobody at the cooperative could read its message, and forty farmers were paid a week late.

The file was written in JSON, the format most programs use to send data to each other. Its rules are few and strict, and its error messages say exactly where the problem is. This lesson teaches you both.

The idea

Data that travels as text

A request and a response carry text. So when one program sends data to another, the data must be written as text first, and turned back into data at the other end. Both programs must agree on how.

JSON, short for JavaScript Object Notation, is that agreement. It looks like the arrays and objects you wrote in module 4, so you can already read most of it:

From delivery.js
const deliveryText = `{
  "week": "2026-11-09",
  "farmer": { "name": "Ruth Kaupa", "village": "Asaro" },
  "bags": [
    { "grade": "A", "weightKg": 60 },
    { "grade": "A", "weightKg": 58 },
    { "grade": "AB", "weightKg": 61 }
  ],
  "paid": false
}`;

Here the JSON is a template literal in a script, so you can try it without a server. The backticks let the text run over several lines. In lesson 3 the same kind of text arrives from a server on the internet.

The rules

JSON is stricter than JavaScript. These are all of its rules that you need:

  • Every property name is in double quotes: "week", never week.
  • Every string is in double quotes too. Single quotes are not allowed.
  • A value is a string, a number, true, false, null (nothing), an object in { } or an array in [ ].
  • Items are separated by commas, and there is no comma after the last one.
  • There are no comments.

Objects and arrays can sit inside each other as deep as you need. That is called nested data. Above, farmer is an object inside the delivery, and bags is an array of objects.

JSON.parse and JSON.stringify

To your script, deliveryText is only a string, a row of characters. You cannot ask a string for its farmer. JSON.parse reads the text and builds the real objects and arrays:

From delivery.js
const delivery = JSON.parse(deliveryText);

To parse means to read text and work out its structure. JSON.stringify goes the other way. It takes a value and writes it as JSON text, ready to send:

From delivery.js
console.log(JSON.stringify(delivery));

console.log writes a line in the Console of the developer tools, which you opened in module 1.

Reading inside nested data

You reach inside with the same dots and square brackets as in module 4, one level at a time:

  • delivery.farmer is the object { "name": "Ruth Kaupa", "village": "Asaro" }.
  • delivery.farmer.name is the string "Ruth Kaupa".
  • delivery.bags is the array of three bags. delivery.bags.length is 3.
  • delivery.bags[0] is the first bag. Positions in an array start at 0.
  • delivery.bags[0].weightKg is 60.

Read the path from left to right and say each step aloud: "the delivery, its bags, the first one, its weight". When a path does not work, the step where it stops making sense is the step that is wrong.

Worked example

Grace wants a page that shows the delivery as a person would read it, from the same text the buyer receives. Make a folder called delivery with two files. First index.html:

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Delivery, Highlands Coffee Growers</title>
    <script src="delivery.js" defer></script>
  </head>
  <body>
    <main>
      <h1>This week's delivery</h1>
      <p id="summary"></p>
      <p id="first-bag"></p>
      <p id="total"></p>
    </main>
  </body>
</html>

Then delivery.js:

delivery.js
// The same text the buyer's program receives. Backticks let it run over several lines.
const deliveryText = `{
  "week": "2026-11-09",
  "farmer": { "name": "Ruth Kaupa", "village": "Asaro" },
  "bags": [
    { "grade": "A", "weightKg": 60 },
    { "grade": "A", "weightKg": 58 },
    { "grade": "AB", "weightKg": 61 }
  ],
  "paid": false
}`;

const delivery = JSON.parse(deliveryText);

document.querySelector("#summary").textContent =
  `${delivery.farmer.name} from ${delivery.farmer.village} delivered ${delivery.bags.length} bags.`;

const firstBag = delivery.bags[0];
document.querySelector("#first-bag").textContent = `First bag: grade ${firstBag.grade}, ${firstBag.weightKg} kg`;

let totalKg = 0;
for (const bag of delivery.bags) {
  totalKg = totalKg + bag.weightKg;
}
document.querySelector("#total").textContent = `Total: ${totalKg} kg`;

delivery.paid = true;
console.log(JSON.stringify(delivery));

Save both, open index.html in your browser, and open the Console. The page shows:

Output
This week's delivery

Ruth Kaupa from Asaro delivered 3 bags.

First bag: grade A, 60 kg

Total: 179 kg

And the Console shows one long line:

Output
{"week":"2026-11-09","farmer":{"name":"Ruth Kaupa","village":"Asaro"},"bags":[{"grade":"A","weightKg":60},{"grade":"A","weightKg":58},{"grade":"AB","weightKg":61}],"paid":true}

Line 13 turns the text into objects. From there on, everything is the JavaScript you know. Line 18 keeps the first bag in a variable, so line 19 stays short. Lines 21 to 24 add up the weights with a loop. A number in JSON arrives as a number, so + adds it.

Line 27 changes paid to true, and line 28 writes the whole delivery back as text. It has no spaces or line breaks, and "paid" is now true. This is how the delivery would travel back to another program.

Common mistakes

A missing quotation mark

This is Grace's mistake, in missing-quote.js. The quotation mark after Kaupa is missing:

From missing-quote.js
  "farmer": { "name": "Ruth Kaupa, "village": "Asaro" },

The page stays empty, and the Console shows:

Output
page error: Uncaught SyntaxError: Expected ',' or '}' after property value in JSON at position 62 (line 3 column 37)

Read the message from the end. Line 3, column 37 of the JSON text is the v of village. The parser read "Ruth Kaupa, " as one string. It then expected a comma or the end of the object, and found a letter. The real mistake is a little before the place the message names, so look left from column 37. Firefox words the message differently, and it also names a line and a column.

A comma after the last item

From trailing-comma.js
  "paid": false,
}`;
Output
page error: Uncaught SyntaxError: Expected double-quoted property name in JSON at position 101 (line 5 column 1)

After a comma, JSON expects another property, which starts with a double quote. It found } at line 5, column 1. JavaScript allows that last comma, and JSON does not. Delete it.

Forgetting the position in an array

From no-position.js
document.querySelector("#first-bag").textContent = `First bag: ${delivery.bags.weightKg} kg`;

There is no error. The page shows:

Output
First bag: undefined kg

undefined is JavaScript's word for "there is nothing here". Say the path aloud: "the delivery, its bags, its weight". The list of bags has no weight. Each bag in it does. Add the position: delivery.bags[0].weightKg.

Think it through

Kiri, a learner, asks the weather service from lesson 1 for the highest temperature of the next three days in Goroka. The answer contains this, among other parts: "daily": { "time": ["2026-11-16", "2026-11-17", "2026-11-18"], "temperature_2m_max": [25.3, 26.3, 23.2] }. Kiri wants tomorrow's date and temperature.

Understand. In: the JSON text of the answer. Out: two values, the date and the temperature for tomorrow.

Break down. Parse the text. Find the daily object. Find the right position in each of its two arrays.

Plan. After const forecast = JSON.parse(text), the dates are forecast.daily.time and the temperatures are forecast.daily.temperature_2m_max. The arrays are in the same order, so position 0 is today in both, and position 1 is tomorrow.

Build. Kiri writes forecast.daily.time[1] and forecast.daily.temperature_2m_max[1], and logs both.

Test. The Console shows 2026-11-17 and 26.3, which match the text by eye. For an odd case, Kiri tries position 3 and gets undefined, because three days means positions 0, 1 and 2.

Reflect. The answer is not an array of day objects. It is two arrays that line up. Kiri writes that down, because it decides how every loop over this answer must work.

At work

When you present your work, show it working first. Explanations make sense once the person has seen the result.

Peter, the developer who built Grace's page, did not start with JSON. He opened the page on Grace's laptop and said:

Here is this week's delivery as a page: Ruth Kaupa, three bags, 179 kilograms. It is made from the same file the buyer's program reads, so if this page shows the right numbers, the buyer sees them too.

If the file has a mistake, the page stays empty and the developer tools say which line and which column to look at. I will show you where to find that message.

Grace saw her own numbers before she heard the word JSON. The explanation then answered a question she already had: how do I know the file is right?

Your tasks

Task 1: JSON in the Console

Open any page, then open the Console. Type JSON.parse('{"bags": 3}') and press Enter. Then type JSON.stringify({ village: "Asaro" }) and press Enter. Here the outer quotes are single, so the double quotes inside them are part of the text.

You are done when you have seen an object come back from the first line and a string with double quotes around village from the second.

Task 2: Build the page and add a bag

Build the worked example. Then add a fourth bag of grade AB that weighs 59 kg to the JSON text.

You are done when the page says 4 bags and a total of 238 kg, and you changed nothing outside the JSON text.

Task 3: Break it on purpose

Remove the quotation mark at the start of "village", save and reload. Read the message in the Console, find the line and column it names, and put the quote back. Then do the same with the comma after "Asaro" }.

You are done when you can say, for each message, how far its column was from the character you removed.

Task 4: One line per bag

Add an empty ul to the page. Fill it with one list item per bag, such as "Grade A, 60 kg", using a loop. Below the list, show "Paid" or "Not paid yet", decided by the paid value with if and else.

You are done when the page lists three bags and says "Not paid yet", and changing "paid": false to "paid": true in the text changes it to "Paid".

Recap

  • JSON is data written as text, so programs can send it to each other. It looks like JavaScript's arrays and objects.
  • Every name and every string is in double quotes, and there is no comma after the last item.
  • JSON.parse turns text into values. JSON.stringify turns values into text.
  • Read a nested path one step at a time. undefined means one step found nothing.
  • A JSON error names a line and a column. The mistake is at that place or just before it.

Go deeper