Loading

T9 APIs · Lesson 2

JSON

JSON is the packing that almost every API uses for its data: a strict little text format that any language can read. Learn its six kinds of value and its rules, turn data into JSON and back with all the options, send and receive it over HTTP, check what a client sent, and design shapes of data that age well.

  • write valid JSON, and say why a text is not JSON
  • turn data into JSON with JSON.stringify: indentation, a replacer, toJSON, and what is left out
  • turn JSON back into data with JSON.parse and a reviver, and keep large numbers safe
  • send and receive JSON over HTTP, with its Content-Type, and answer 415 to anything else
  • check a JSON body and answer 400 with every problem at once
  • design JSON shapes that age well: names, dates, money and lists
About 60 minutesChecked against Node.js on the laptop (the kit runs every code block with it) 22.23.1 (2026-11-14); GNU Bash on the laptop (the kit compares every shell block with it, in a sandbox) 5.3.9 (2026-11-14)Play this lesson's games

The back cover

Every parcel that crosses the network needs packing, and almost every API packs its data the same way: JSON. It is a strict little text format, and any language can read it. A parcel packed badly arrives broken, or not at all.

These pages show JSON's six kinds of value and its rules. They turn data into JSON and back with all the options, send it over HTTP with the right label, check every body that arrives, and design shapes of data that still make sense years later. Each step guards against a real way that data goes wrong.

Before you start

The story: The parcel that changed on the way

The Clock Tower sent the Engine Hall a parcel of last night's readings. When the Foreman opened it, the numbers had become words, the times made no sense, and one reading was missing altogether.

Nobody had lost anything. The Clock Tower had packed the parcel its own way, and the Engine Hall had unpacked it another way.

Yardmaster Waybill sets the parcel on her bench. "Every hall in this city packs differently," she says, "so the yard has one packing for every parcel. Learn it, and a parcel opens the same at the other end as it was packed."

An API's answers are data, and data must travel as text: a request or a response is only characters on a wire. JSON is the way almost every API packs its data into text, and unpacks it again at the other end.

You have used JSON since the JavaScript track. This lesson looks at it closely, as an API builder must: its exact rules, every option of the two functions that pack and unpack it, and the mistakes that make data change on the way.

It builds on these ideas. Each one has a tiny example, so you can check that you remember it.

What you already knowA tiny exampleWhere it comes back
Objects and arrays.{ name: "boiler", parts: [] }What JSON packs.
JSON.stringify and JSON.parse.JSON.parse('{"a":1}')Every option of each.
typeof.typeof 95Checking what arrived.
Dates.new Date(0).toISOString()Times travel as text.
Classes.class Reading { }toJSON, a method of your own.
try and catch.try { } catch (e) { e.name }Text that is not JSON.
Content-Type.application/jsonThe label on every parcel.
Status codes.400, 404415, for the wrong kind of body.
A server and its client.http.createServerJSON over HTTP.
Floating point.0.1 + 0.2Why money is counted in paise.

By the end of this lesson you will be able to:

  • write valid JSON, and say why a text is not JSON;
  • turn data into JSON with JSON.stringify: indentation, a replacer, toJSON, and what is left out;
  • turn JSON back into data with JSON.parse and a reviver, and keep large numbers safe;
  • send and receive JSON over HTTP, with its Content-Type, and answer 415 to anything else;
  • check a JSON body and answer 400 with every problem at once;
  • design JSON shapes that age well: names, dates, money and lists.

How to follow this lesson

Every block runs on the page, in the small Node, and has also been run in real Node 22, where it prints the same. When a text is not JSON, the blocks print the error's name, SyntaxError, and never its message: the message's wording changes from one version of JavaScript's engine to the next, so the page's browser and Node word it differently.

In one line

This lesson is about JSON: its format and rules, JSON.stringify and JSON.parse in depth, JSON over HTTP, checking a body, and designing shapes of data.

The JSON format

At a glance

Almost every API packs its data in JSON. It is a strict little text format that any language can read and write.

A JSON text holds one value, and a value is one of six kinds: a string, a number, true or false, null, an array or an object. Arrays and objects can hold more values inside them. The rules are strict. Names and strings take double quotes. There is no comma after the last item, no comment, no leading zero on a number, and no NaN.

Take a guess: Does the JSON standard limit how deep a JSON text may nest?

JSON, JavaScript Object Notation, is a way to write data as text. It borrowed the look of JavaScript's objects and arrays, but it is stricter, and it belongs to no one language: Python, Java, Go and every other language can read and write it. Its rules are written down in a standard, RFC 8259.

Six kinds of value

A JSON text holds one value, and a value is one of six kinds. Objects and arrays may hold more values inside them, to any depth:

KindExampleRule
string"boiler 95"always double quotes
number95, 3.5, -2e3no leading zeros; no NaN or Infinity
true or falsetruesmall letters
nullnullnothing, on purpose
array[95, "x", null]values in square brackets, between commas
object{ "name": "boiler" }names in double quotes, then a colon and a value

JSON.parse turns a JSON text into data. The kinds come back as JavaScript's own: a number is a number, an array is an array, null is null:

app.js

const data = JSON.parse('{"n": 1.5, "b": true, "z": null, "s": "x", "a": [1, "2"], "o": {}}');
console.log(data);
console.log(typeof data.n, typeof data.a[1], Array.isArray(data.a));

Terminal: node app.js

{ n: 1.5, b: true, z: null, s: 'x', a: [ 1, '2' ], o: {} }
number string true

Look at a[1]: it came back as the string '2', because the JSON text wrote it in quotes. JSON keeps the kind that was written.

What JSON refuses

Many texts that look like JavaScript are not JSON. This program offers eleven texts to JSON.parse, and prints ok or the error's name for each:

app.js

const samples = ["{'a': 1}", '{"a": 1,}', "{a: 1}", "[1, 2", "// note\n{}", '{"a": 01}', '{"a": NaN}', ' { "a" : 1 } ', '"text"', "true", "[]"];
for (const s of samples) {
  try {
    JSON.parse(s);
    console.log("ok   ", JSON.stringify(s));
  } catch (e) {
    console.log(e.name, JSON.stringify(s));
  }
}

Terminal: node app.js

SyntaxError "{'a': 1}"
SyntaxError "{\"a\": 1,}"
SyntaxError "{a: 1}"
SyntaxError "[1, 2"
SyntaxError "// note\n{}"
SyntaxError "{\"a\": 01}"
SyntaxError "{\"a\": NaN}"
ok    " { \"a\" : 1 } "
ok    "\"text\""
ok    "true"
ok    "[]"

The first seven were refused, each for one rule: single quotes; a comma after the last item; a name without quotes; a missing bracket; a comment; a number with a leading zero; and NaN, which JSON does not know.

The last four were accepted. Spaces and new lines between parts are allowed, and a JSON text may be a lone string, true, or an empty array: any one value.

RuleValidNot JSON
names in double quotes{ "a": 1 }{ a: 1 }, { 'a': 1 }
strings in double quotes"text"'text'
no comma after the last item[1, 2][1, 2,]
no comments{}// note before it
numbers as written in maths1, 0.501, .5, NaN

Worked example 1

A settings file was written by hand, as { name: 'boiler', limit: 90, }. JSON.parse refuses it. Find every rule it breaks, and fix it.

What we have: the text { name: 'boiler', limit: 90, }

What we need: the same data as valid JSON

The plan: check the text against each rule; correct each fault; parse both texts to compare

app.js

const before = "{ name: 'boiler', limit: 90, }";
const after = '{ "name": "boiler", "limit": 90 }';
for (const text of [before, after]) {
  try {
    console.log("parsed:", JSON.parse(text));
  } catch (e) {
    console.log(e.name, "in", text);
  }
}

Terminal: node app.js

SyntaxError in { name: 'boiler', limit: 90, }
parsed: { name: 'boiler', limit: 90 }
  1. The names name and limit had no quotes: JSON needs double quotes around every name.
  2. The string 'boiler' used single quotes: JSON needs double quotes.
  3. A comma followed the last item, 90: JSON allows none there.

Three faults: unquoted names, single quotes and a last comma. Fixed, the text parses.

Check: The fixed text gives back exactly the data that the hand-written one meant: name boiler, limit 90.

A path that fails: fixing only the first error that you notice and trying again. Each try shows one fault at a time; checking every rule at once finds all three in one pass.

When you are stuck: JSON.parse says SyntaxError

Print the text with JSON.stringify(text): every hidden character and quote shows.

Check the rules in order: double quotes on every name and string, no last comma, no comments, plain numbers.

An empty text, or one that is cut short, is not JSON either.

Your turn

Is {'gauge': 'boiler'} valid JSON?Tap to reveal
  1. Which quotes does JSON use?

No: JSON needs double quotes, for names and for strings.

Which of these is valid JSON: [1, 2,] or [1, 2]?Tap to reveal
  1. Look at the end.

[1, 2]: JSON allows no comma after the last item.

node -p 'typeof JSON.parse("[1, 2]")'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
object
  1. JSON.parse gives back a JavaScript array.
  2. typeof says object for an array.

It prints object.

Did you know?

Each parser sets its own limits

The JSON standard sets no size limits of its own. RFC 8259 says that an implementation may set limits on the size of the texts it accepts, on the maximum depth of nesting, on the range and precision of numbers, and on the length and contents of strings. So a JSON text that one program reads may be refused by another.

Why it fits here: It answers this topic's question: the standard leaves limits on depth, size and numbers to each parser, so they differ.

Source: RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format

Not quite a subset, until 2019

For years, JSON was not quite a part of JavaScript. The TC39 proposal JSON superset explains why: JSON strings could hold two invisible characters unescaped, U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR, while JavaScript strings could not. The proposal extended JavaScript into a superset of JSON, and it was scheduled for ES2019.

Why it fits here: It sharpens this topic's format: until ES2019, two characters made some JSON texts invalid JavaScript.

Source: TC39 proposal: Subsume JSON

In one line

JSON holds one value of six kinds: string, number, true or false, null, array, object; names and strings take double quotes, and there are no last commas, comments, leading zeros or NaN.

JSON.stringify in depth

At a glance

JSON.stringify turns JavaScript data into JSON text, ready to travel. It does more than copy. Knowing what it does keeps data from vanishing on the way.

It leaves out undefined, functions and symbols, turns NaN into null, and writes a Date as ISO text. A second argument, the replacer, chooses which names or values go in. A third, space, indents the text so that people can read it. And an object with a toJSON method decides its own JSON. A BigInt, or an object that holds itself, makes it throw a TypeError.

Take a guess: Can JSON.stringify write a number bigger than JavaScript's safe whole numbers?

The function JSON.stringify(value) turns data into a JSON text. This is called serializing: laying the data out as a series of characters. Most data goes across unchanged; some does not, and an API builder must know which.

What changes on the way

app.js

console.log(JSON.stringify({ a: undefined, f() {}, s: Symbol("x"), n: NaN, i: Infinity, d: new Date(0), nested: { ok: true } }));
console.log(JSON.stringify([undefined, () => 1, NaN, "x"]));
console.log(JSON.stringify("text"), JSON.stringify(42), JSON.stringify(null), JSON.stringify(undefined));
console.log(JSON.stringify("₹40"), JSON.stringify("line\nnext"), JSON.stringify('say "hi"'));

Terminal: node app.js

{"n":null,"i":null,"d":"1970-01-01T00:00:00.000Z","nested":{"ok":true}}
[null,null,null,"x"]
"text" 42 null undefined
"₹40" "line\nnext" "say \"hi\""

Inside an object, undefined, functions and symbols are left out altogether: a, f and s are missing. NaN and Infinity, which JSON has no way to write, became null. The Date became text, in the standard ISO form. Inside an array, the left-out values became null instead, so that the other items keep their places.

A string is written with its quotes, and a new line or a quote inside it is written with a backslash. The rupee sign travels as it is.

In the dataIn the JSON
undefined, a function, a symbol, in an objectleft out
the same, in an arraynull
NaN, Infinitynull
a Dateits time as ISO text, such as "1970-01-01T00:00:00.000Z"
10n, a BigInta TypeError: JSON has no such number
an object that holds itselfa TypeError: the text would never end

Indentation and the replacer

JSON.stringify takes two more arguments. The third, space, indents the text for people to read: a number of spaces, or a string such as "\t". The second, the replacer, chooses what goes in. An array of names keeps only those names. A function is called for every name and value, and what it returns goes in; returning undefined leaves that value out:

app.js

const pump = { name: "pump 2", pressure: 3.5, secret: "x7", open: true, parts: ["valve", "seal"] };
console.log(JSON.stringify(pump, null, 2));
console.log(JSON.stringify(pump, ["name", "pressure"]));
console.log(JSON.stringify(pump, (key, value) => (key === "secret" ? undefined : value)));

Terminal: node app.js

{
  "name": "pump 2",
  "pressure": 3.5,
  "secret": "x7",
  "open": true,
  "parts": [
    "valve",
    "seal"
  ]
}
{"name":"pump 2","pressure":3.5}
{"name":"pump 2","pressure":3.5,"open":true,"parts":["valve","seal"]}

APIs send compact JSON, with no indentation, as the spaces cost bytes and only programs read it. Indentation is for files and logs that people read.

toJSON: an object decides its own JSON

If an object has a method called toJSON, JSON.stringify calls it and writes what it returns instead. A Date has one, which is why dates become text. A class can have its own:

app.js

class Reading {
  constructor(gauge, value) {
    this.gauge = gauge;
    this.value = value;
    this.at = new Date(Date.UTC(2026, 10, 9, 6, 30));
  }
  toJSON() {
    return { gauge: this.gauge, value: this.value, at: this.at };
  }
}
const r = new Reading("boiler", 95);
r.cache = "not sent";
console.log(JSON.stringify(r));
try { JSON.stringify({ n: 10n }); } catch (e) { console.log(e.name); }
const loop = { name: "a" };
loop.self = loop;
try { JSON.stringify(loop); } catch (e) { console.log(e.name); }

Terminal: node app.js

{"gauge":"boiler","value":95,"at":"2026-11-09T06:30:00.000Z"}
TypeError
TypeError

The field cache was left out, because toJSON returned only three fields. The date inside them went through its own toJSON. The two TypeErrors are the BigInt and the object that holds itself, which JSON cannot write.

Worked example 2

The hall's user records hold a password and a token, which must never leave the server. Turn a user into JSON for an API's answer, without them, indented for a log.

What we have: a user object with name, hall, password, token and joined

What we need: the JSON of every field except password and token

The plan: a replacer function that returns undefined for the two secret names, and the value for every other; two spaces of indentation

app.js

const user = { name: "Asha", hall: "Engine Hall", password: "c0g-wheel", token: "t-91", joined: new Date(Date.UTC(2026, 0, 5)) };
const hidden = new Set(["password", "token"]);
const text = JSON.stringify(user, (key, value) => (hidden.has(key) ? undefined : value), 2);
console.log(text);

Terminal: node app.js

{
  "name": "Asha",
  "hall": "Engine Hall",
  "joined": "2026-01-05T00:00:00.000Z"
}
  1. The Set of hidden names makes the rule one line, and a new secret field is one more word in it.
  2. The replacer is called for every name, at every depth, so a password nested inside another object would be left out too.
  3. joined, a Date, became ISO text by its own toJSON.

Three fields in the JSON: name, hall and joined; no password, no token.

Check: Count the fields: five went in, two were hidden, three came out.

A path that fails: a replacer array that lists the fields to keep, written once and forgotten. A field added to users later, such as phone, is then left out silently; the function that hides named secrets lets new fields through on purpose, and a safe API decides which way it wants.

When you are stuck: A field is missing from the JSON

Was its value undefined, a function or a symbol? Those are left out.

Does the object have a toJSON method, or did a replacer return undefined for it?

A Date became text, and NaN became null: JSON.parse will not give them back as they were.

Your turn

What does JSON.stringify({ a: undefined, b: 1 }) give?Tap to reveal
  1. undefined is left out of an object.

'{"b":1}'.

Which argument of JSON.stringify chooses which values go in?Tap to reveal
  1. It is the second one.

The replacer: an array of names, or a function.

node -p 'JSON.stringify([NaN, 1])'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
[null,1]
  1. JSON has no NaN.
  2. In an array, it becomes null.

It prints [null,1].

Did you know?

JSON.rawJSON keeps every digit

A big number can now travel whole. JSON.rawJSON makes an object that holds a piece of JSON text, and JSON.stringify writes that text exactly as it is. So JSON.stringify({ id: JSON.rawJSON("12345678901234567890") }) keeps all twenty digits, which a JavaScript number would round. MDN marks it Baseline 2025: it works in the latest browsers since March 2025.

Why it fits here: It answers this topic's question: with JSON.rawJSON, JSON.stringify writes a long number digit for digit.

Sources: MDN: JSON.rawJSON(); TC39 proposal: JSON.parse source text access

Lone surrogates come out escaped

JSON.stringify once could produce text that UTF-8 cannot carry. A lone surrogate, a code unit from U+D800 to U+DFFF without its partner, was written out as it was. The TC39 proposal Well-formed JSON.stringify fixed this, and MDN says that engines with the fix write such a character as an escape sequence instead, so JSON.stringify("\uD800") gives "\ud800".

Why it fits here: It adds to this topic's JSON.stringify: a lone surrogate now comes out as an escape, so the text is valid UTF-8.

Sources: MDN: JSON.stringify(); TC39 proposal: Well-formed JSON.stringify

In one line

JSON.stringify leaves out undefined, functions and symbols, turns NaN into null and Dates into ISO text; a replacer chooses what goes in, space indents, and an object's toJSON decides its own JSON.

JSON.parse in depth

At a glance

JSON.parse does the opposite: it turns JSON text back into JavaScript values. It is the step that every client and server takes when data arrives.

It gives back JSON's own kinds only: strings, numbers, true, false, null, arrays and plain objects. A date arrives as a string, so a second argument, the reviver, can turn values back into what they were, such as Date objects. Numbers need care. JavaScript's numbers are exact for whole numbers only up to Number.MAX_SAFE_INTEGER, so larger ids lose digits, and they travel as strings instead.

Take a guess: How do big APIs send ids too long for JavaScript's numbers?

The function JSON.parse(text) turns a JSON text back into data. This is deserializing. It gives back exactly the six kinds that JSON knows, so whatever stringify changed on the way stays changed: a Date that became text comes back as text.

app.js

console.log(JSON.parse('{"a":1,"a":2}'), JSON.parse(' "just text" '), JSON.parse("42"), JSON.parse("null"));

Terminal: node app.js

{ a: 2 } just text 42 null

A JSON text may be a lone value, such as a string, a number or null. A name written twice in one object is allowed by the parser, which keeps the last one: a was 2. The standard says that names should be unique, so an API should never send such a text.

The reviver: turning text back into what it was

JSON.parse takes a second argument, the reviver: a function of a name and a value, called for every value in the text. What it returns is kept in that value's place. A reviver can turn a date's text back into a Date:

app.js

const text = '{"gauge":"boiler","value":95,"at":"2026-11-09T06:30:00.000Z"}';
const plain = JSON.parse(text);
console.log(typeof plain.at);
const revived = JSON.parse(text, (key, value) => (key === "at" ? new Date(value) : value));
console.log(revived.at instanceof Date, revived.at.getUTCHours(), revived.at.toISOString());

Terminal: node app.js

string
true 6 2026-11-09T06:30:00.000Z

Without the reviver, at was a string. With it, at is a real Date, whose hours and methods work. The reviver is called for the innermost values first and the whole object last, so it can rebuild any value at any depth.

Numbers too large to be exact

JavaScript's numbers are exact for whole numbers only up to Number.MAX_SAFE_INTEGER, which is 9,007,19,92,54,740,991 in Indian grouping, a sixteen-digit number. Above it, a number is rounded to the nearest one that JavaScript can store, without any warning:

app.js

console.log(JSON.parse('{"id": 9007199254740993}').id, Number.MAX_SAFE_INTEGER);
console.log(JSON.parse('{"id": "9007199254740993"}').id);

Terminal: node app.js

9007199254740992 9007199254740991
9007199254740993

The id 9007199254740993 came back one less than it was sent. Such numbers are common as ids, so APIs send large ids as strings, which JSON keeps exactly, as the second line shows.

Sent asAfter JSON.parseKeep it right by
a date's ISO texta stringa reviver, or new Date(value) where it is used
a large id, as a numbera rounded numbersending ids as strings
a name twice in one objectthe last valuenever sending duplicates
NaN or Infinity, sent by stringifynullchecking before sending

Worked example 3

Two boiler readings arrive as JSON, each with its time as ISO text. How many minutes apart were they taken?

What we have: a JSON array of two readings, at 06:30 and 07:15 UTC

What we need: the gap between them, in minutes

The plan: parse with a reviver that turns at into a Date; subtract the two Dates, which gives milliseconds; divide by 60,000

app.js

const text = '[{"gauge":"boiler","at":"2026-11-09T06:30:00.000Z"},{"gauge":"boiler","at":"2026-11-09T07:15:00.000Z"}]';
const readings = JSON.parse(text, (key, value) => (key === "at" ? new Date(value) : value));
const minutes = (readings[1].at - readings[0].at) / 60000;
console.log(`${minutes} minutes between the readings`);

Terminal: node app.js

45 minutes between the readings
  1. Subtracting one Date from another gives the milliseconds between them.
  2. A minute has 60 × 1,000 = 60,000 milliseconds.
  3. The reviver ran for every at inside the array, at any depth.

45 minutes between the readings.

Check: From 06:30 to 07:15 is 45 minutes, counted on a clock.

A path that fails: subtracting the two at values without a reviver. They are strings, so the subtraction gives NaN, and the answer prints as NaN minutes.

When you are stuck: Data came back different from what was sent

Dates come back as text: revive them, or call new Date where they are used.

Large whole numbers above Number.MAX_SAFE_INTEGER lose their last digits: send them as strings.

Values that stringify left out or turned into null cannot come back; check the data before it is sent.

Your turn

What does JSON.parse give for a date that was sent as ISO text?Tap to reveal
  1. JSON has no date kind.

A string, until a reviver or new Date turns it into a Date.

Why do many APIs send ids as strings?Tap to reveal
  1. Think of 9007199254740993.

Large numbers lose precision; a string keeps every digit.

node -p 'JSON.parse("[1, 2]", (k, v) => (typeof v === "number" ? v * 10 : v))'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
[ 10, 20 ]
  1. The reviver is called for each value.
  2. Each number is multiplied by 10; the array is returned as it is.

It prints [ 10, 20 ].

Did you know?

X sends its ids as text

A large API follows the rule for ids. X's developer documentation says to always use string ids, because some languages, like JavaScript, cannot accurately represent 64-bit integers: JavaScript's integers are limited to 53 bits. So version 2 of its API returns ids as strings by default, and version 1.1 gave each id twice, as id, a number, and id_str, a string.

Why it fits here: It answers this topic's question: X sends its 64-bit ids as strings, as JavaScript's numbers are exact only to 53 bits.

Source: X Developer Platform: X IDs

A reviver that sees the digits

A reviver can now see the text that a value came from. MDN describes a third argument for the reviver, context, whose source field holds the original JSON text of a primitive value. So a reviver can build a BigInt from a long number's own digits, before any rounding happens. The TC39 proposal behind it, JSON.parse source text access, has reached stage 4.

Why it fits here: It adds to this topic's reviver: its third argument holds a number's original digits, so a long id need not lose any.

Sources: MDN: JSON.parse(); TC39 proposal: JSON.parse source text access

In one line

JSON.parse gives back JSON's own kinds; a reviver turns values back into what they were, such as Dates; whole numbers above Number.MAX_SAFE_INTEGER lose precision, so large ids travel as strings.

JSON over HTTP

At a glance

JSON crosses the network in the body of a request or a response. A label says what the body is.

The label is the header Content-Type: application/json. A client sends JSON.stringify(data) with that label. A server checks the label first, and answers 415 Unsupported Media Type to any other kind of body, and 400 Bad Request to JSON that will not parse. On the other side, a client calls json() only on a body that is JSON, and only once.

Take a guess: Does application/json need a charset, as text/plain has?

A JSON text travels in the body of a request or a response. The body is only characters, so a header must say what kind of text it is. That header is Content-Type, and for JSON its value is application/json. Both sides of an API use it: the client puts it on every body it sends, and the server puts it on every body it answers.

What fetch sends

fetch takes a body in several forms, and labels each one by itself. The server here prints the label it received and the body with it, for five ways of sending the same data:

app.js

const http = require("http");
const server = http.createServer(async (req, res) => {
  let body = "";
  for await (const chunk of req) body += chunk;
  res.end(`${req.headers["content-type"]} | ${body}`);
});
server.listen(3000, async () => {
  const sends = [
    { body: JSON.stringify({ name: "fan" }) },
    { headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "fan" }) },
    { headers: { "Content-Type": "application/json" }, body: { name: "fan" } },
    { body: new URLSearchParams({ name: "fan", value: "20" }) },
    { body: 42 },
  ];
  for (const init of sends) {
    const r = await fetch("http://localhost:3000/gauges", { method: "POST", ...init });
    console.log(await r.text());
  }
  server.close();
});

Terminal: node app.js

text/plain;charset=UTF-8 | {"name":"fan"}
application/json | {"name":"fan"}
application/json | [object Object]
application/x-www-form-urlencoded;charset=UTF-8 | name=fan&value=20
text/plain;charset=UTF-8 | 42

The first send gave a string with no header, so fetch labelled it plain text; the server would have to guess that it is JSON. The second gave the header, and the body was labelled as JSON.

The third is the mistake to remember: the object was never given to JSON.stringify, so fetch turned it into its text, which is [object Object], and the server got no data at all. A URLSearchParams body goes as a form, and a number goes as its text.

So the rule for sending JSON has two halves: body: JSON.stringify(data) and headers: { "Content-Type": "application/json" }, always together.

What the server checks

A server reads the label before the body. If the label is not JSON, the right answer is 415 Unsupported Media Type: the request's body is of a kind that this endpoint does not take. If the label is right and the text is still not JSON, the answer is 400 Bad Request, as in lesson 01:

app.js

const http = require("http");
const isJSON = (type = "") => type.split(";")[0].trim().toLowerCase() === "application/json";
const server = http.createServer(async (req, res) => {
  const send = (status, data) => {
    res.writeHead(status, { "Content-Type": "application/json" });
    res.end(JSON.stringify(data));
  };
  if (!isJSON(req.headers["content-type"])) return send(415, { error: "send JSON, with Content-Type: application/json" });
  let body = "";
  for await (const chunk of req) body += chunk;
  let data;
  try {
    data = JSON.parse(body);
  } catch {
    return send(400, { error: "the body is not valid JSON" });
  }
  send(200, { got: data });
});
server.listen(3000, async () => {
  const tries = [
    ["text/plain", '{"v":1}'],
    ["application/json", "{v:1}"],
    ["application/json; charset=utf-8", '{"v":1}'],
    ["Application/JSON", '{"v":2}'],
  ];
  for (const [type, body] of tries) {
    const r = await fetch("http://localhost:3000/readings", { method: "POST", headers: { "Content-Type": type }, body });
    console.log(r.status, r.statusText, JSON.stringify(await r.json()));
  }
  server.close();
});

Terminal: node app.js

415 Unsupported Media Type {"error":"send JSON, with Content-Type: application/json"}
400 Bad Request {"error":"the body is not valid JSON"}
200 OK {"got":{"v":1}}
200 OK {"got":{"v":2}}

The label can carry more than the type: application/json; charset=utf-8 is JSON too, and so is Application/JSON, because the type's letters are compared without regard to case. The helper isJSON keeps the part before the semicolon, trims it and lowers it before comparing, and both of those requests got 200.

The server foundAnswerIt tells the client
a Content-Type that is not JSON415send a JSON body, with the JSON label
the JSON label, and a text that does not parse400the JSON itself is broken
JSON that parses200 or 201the data arrived

Reading an answer

On the client, r.json() reads the body and parses it in one go. It trusts the body to be JSON, so it must only be called when the body is JSON. This client calls it on three answers:

app.js

const http = require("http");
const server = http.createServer((req, res) => {
  if (req.url === "/text") {
    res.setHeader("Content-Type", "text/html");
    return res.end("<h1>Not here</h1>");
  }
  if (req.url === "/empty") {
    res.statusCode = 204;
    return res.end();
  }
  res.setHeader("Content-Type", "application/json");
  res.end('{"value":95}');
});
server.listen(3000, async () => {
  for (const path of ["/json", "/text", "/empty"]) {
    const r = await fetch("http://localhost:3000" + path);
    try {
      console.log(path, r.status, r.headers.get("content-type"), await r.json());
    } catch (e) {
      console.log(path, r.status, r.headers.get("content-type"), e.name);
    }
  }
  server.close();
});

Terminal: node app.js

/json 200 application/json { value: 95 }
/text 200 text/html SyntaxError
/empty 204 null SyntaxError

The first body was JSON and parsed. The second was an HTML page, and the third was nothing at all, because a 204 has no body; both gave a SyntaxError. A careful client reads the status and the Content-Type first, and calls json() only for a JSON body.

A body can be read once. After json() or text(), bodyUsed is true, and a second read is a TypeError. If both the text and the data are needed, read the text, then parse it:

app.js

const http = require("http");
const server = http.createServer((req, res) => {
  res.setHeader("Content-Type", "application/json");
  res.end(JSON.stringify({ accept: req.headers.accept, type: req.headers["content-type"] ?? null }));
});
server.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/gauges", { headers: { Accept: "application/json" } });
  console.log(await r.json());
  const s = await fetch("http://localhost:3000/gauges");
  console.log(await s.json(), s.bodyUsed);
  try { await s.json(); } catch (e) { console.log(e.name, e.message); }
  server.close();
});

Terminal: node app.js

{ accept: 'application/json', type: null }
{ accept: '*/*', type: null } true
TypeError Body is unusable: Body has already been read

The first request also sent an Accept header, which tells the server the kind of answer the client wants. Without it, fetch sends */*, which means any kind. An API that can answer in more than one form reads Accept; most APIs answer JSON whatever it says.

Worked example 4

Write a helper api(method, path, data) that sends JSON the right way and reads any answer the right way, and use it against a small server whose /help page is plain text.

What we have: a server with GET /gauges (JSON), POST /gauges (JSON, 201 with Location) and GET /help (plain text)

What we need: one function for every call: it labels a JSON body, asks for JSON, and parses the body only when the answer is JSON

The plan: build the headers: Accept always, Content-Type only when there is data; stringify the data; read the answer's Content-Type and choose json() or text(); return the status and the body together

app.js

const http = require("http");
const gauges = { boiler: 95, pump: 40 };
const server = http.createServer(async (req, res) => {
  let body = "";
  for await (const chunk of req) body += chunk;
  if (req.url === "/help") {
    res.writeHead(200, { "Content-Type": "text/plain" });
    return res.end("GET /gauges, POST /gauges");
  }
  if (req.method === "POST") {
    const data = JSON.parse(body);
    gauges[data.name] = data.value;
    res.writeHead(201, { "Content-Type": "application/json", Location: `/gauges/${data.name}` });
    return res.end(JSON.stringify(data));
  }
  res.writeHead(200, { "Content-Type": "application/json" });
  res.end(JSON.stringify(gauges));
});
async function api(method, path, data) {
  const r = await fetch("http://localhost:3000" + path, {
    method,
    headers: { Accept: "application/json", ...(data !== undefined && { "Content-Type": "application/json" }) },
    body: data === undefined ? undefined : JSON.stringify(data),
  });
  const type = r.headers.get("content-type") ?? "";
  const body = type.startsWith("application/json") ? await r.json() : await r.text();
  return { status: r.status, body };
}
server.listen(3000, async () => {
  console.log(await api("GET", "/gauges"));
  console.log(await api("POST", "/gauges", { name: "fan", value: 20 }));
  console.log(await api("GET", "/help"));
  server.close();
});

Terminal: node app.js

{ status: 200, body: { boiler: 95, pump: 40 } }
{ status: 201, body: { name: 'fan', value: 20 } }
{ status: 200, body: 'GET /gauges, POST /gauges' }
  1. The spread ...(data !== undefined && { ... }) adds the Content-Type only when there is a body: spreading false adds nothing.
  2. A GET has no body, so body is undefined and fetch sends none.
  3. The answer's label decides how it is read: /help came as text/plain, so text() read it, and no SyntaxError could happen.
  4. The helper returns an object, so one console.log shows the status and the body side by side.

The helper prints 200 with the two gauges, 201 with the new fan, and 200 with the help text, without a single parse error.

Check: Three calls, three answers, each read by its own kind: two parsed as JSON and one kept as text.

Another way: read every body with text() and parse it yourself when the label is JSON; that also lets you print the raw text when parsing fails.

A path that fails: calling r.json() on every answer. The call to /help would throw a SyntaxError, because its body is plain text and not JSON.

When you are stuck: The server got [object Object], or the client got a SyntaxError

Did the client call JSON.stringify on the data? Without it, an object is sent as its text.

Did the client send Content-Type: application/json? Without it, the server may refuse the body with 415.

Did the client call json() on a body that is not JSON, such as an error page or a 204 with no body? Check the status and the Content-Type first.

Your turn

Which two things must a client do to send an object as JSON?Tap to reveal
  1. One is about the body, one is about a header.

Send JSON.stringify(data) as the body, with Content-Type: application/json.

A client sends a form body to an endpoint that takes only JSON. Which status should the server answer?Tap to reveal
  1. The body's kind is wrong, not its content.

415 Unsupported Media Type.

node -p 'JSON.stringify({ name: "fan" }) + " | " + String({ name: "fan" })'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
{"name":"fan"} | [object Object]
  1. JSON.stringify writes the object as JSON text.
  2. String() gives an object's plain text, which is [object Object].

It prints {"name":"fan"} | [object Object].

Did you know?

No charset for JSON

A JSON body needs no charset. RFC 8259 says that JSON text exchanged between systems that are not part of a closed ecosystem must be encoded in UTF-8. It defines no charset parameter for application/json: adding one really has no effect on a recipient that follows the standard. It also forbids a byte order mark at the start of JSON sent over a network.

Why it fits here: It answers this topic's question: JSON between systems is always UTF-8, so application/json has no charset to set.

Source: RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format

The label from 2006

The label application/json comes from RFC 4627, of July 2006, written by Douglas Crockford, which says that the MIME media type for JSON text is application/json. That RFC is now obsolete: RFC 7159 replaced it, and RFC 8259 of December 2017 replaced that in turn. The label stayed the same through all three, so old clients and new ones still agree.

Why it fits here: It dates this topic's label: application/json was registered in 2006 and has not changed since.

Sources: RFC 4627: The application/json Media Type for JavaScript Object Notation (JSON); RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format

In one line

JSON travels in a body labelled Content-Type: application/json. A client sends JSON.stringify(data) with that label; a server answers 415 to any other kind of body and 400 to broken JSON; a client calls json() only on a JSON body, once.

Checking a body

At a glance

JSON that parses is not yet JSON that makes sense. A server checks every body before it trusts it.

It checks the kind of the whole body first: an object, not an array or null. Then it checks each field: typeof for strings, Number.isFinite for numbers, includes for a fixed list of words, and Date.parse for dates. It collects every problem into a list, instead of stopping at the first, and answers 400 with all of them at once. Then the client can fix them all in one go.

Take a guess: Can every engine's Date.parse read the same date texts?

JSON.parse checks only the form of a text: the quotes, the commas, the brackets. It knows nothing about what the data should hold. A reading whose value is the string "95", a gauge with no name, a body that is an array: each one parses, and each one would break the server later.

So an API checks every body before it uses it. This checking is called validation. The client may be any program at all, written by anyone, with any bug, and a server that trusts its clients stops at the first odd request.

A list of problems, not the first one

A good check collects every problem in a list and reports them all at once. A client that is told one mistake at a time has to send the body again for each. The function problems in validate.js returns that list, and an empty list means that the body is good:

validate.js

const units = ["bar", "psi"];
module.exports = function problems(data) {
  const list = [];
  if (typeof data !== "object" || data === null || Array.isArray(data)) return ["the body must be a JSON object"];
  if (typeof data.name !== "string" || data.name.trim() === "") list.push("name must be a non-empty string");
  if (typeof data.value !== "number" || !Number.isFinite(data.value)) list.push("value must be a number");
  else if (data.value < 0 || data.value > 150) list.push("value must be between 0 and 150");
  if (!units.includes(data.unit)) list.push(`unit must be one of: ${units.join(", ")}`);
  return list;
};

app.js

const problems = require("./validate");
for (const data of [{ name: "fan", value: 20, unit: "bar" }, { name: "", value: "20", unit: "kg" }, [1, 2], null, { name: "fan", value: 999, unit: "psi" }]) {
  console.log(JSON.stringify(data), "->", JSON.stringify(problems(data)));
}

Terminal: node app.js

{"name":"fan","value":20,"unit":"bar"} -> []
{"name":"","value":"20","unit":"kg"} -> ["name must be a non-empty string","value must be a number","unit must be one of: bar, psi"]
[1,2] -> ["the body must be a JSON object"]
null -> ["the body must be a JSON object"]
{"name":"fan","value":999,"unit":"psi"} -> ["value must be between 0 and 150"]

The first test is about the whole body, and it needs three parts. typeof gives "object" for null, so null is tested by name; an array is an object too, so Array.isArray is tested as well. A body that fails this test gets one problem and no more, because the field tests would make no sense on it.

Then each field has its test. The value's range is tested with else if, only when the value is a number: a string value gets one problem, not two. The unit is tested with includes against the list of allowed units, and the problem text names them, so the client knows what to send.

To check that a field isTestA problem text
a non-empty stringtypeof x === "string" && x.trim() !== ""name must be a non-empty string
a numbertypeof x === "number" && Number.isFinite(x)value must be a number
in a rangex >= 0 && x <= 150value must be between 0 and 150
one of a listlist.includes(x)unit must be one of: bar, psi
a date in ISO texttypeof x === "string" && !Number.isNaN(Date.parse(x))at must be a date in ISO form
an objecttypeof x === "object" && x !== null && !Array.isArray(x)the body must be a JSON object
a listArray.isArray(x)parts must be a list

Traps in checking

JavaScript's own checks have corners that a validator must know. Each line here prints a check that looks right and is not:

app.js

console.log(typeof null, typeof [], typeof NaN);
console.log(Number.isFinite("20"), Number.isFinite(20), Number.isFinite(NaN));
console.log(Boolean(""), Boolean("false"), Boolean(0));
console.log("20" == 20, "20" === 20);

Terminal: node app.js

object object number
false true false
false true false
true false

typeof null is "object", a slip from JavaScript's first days that was kept so that old pages still work; typeof of an array is "object" too; and typeof NaN is "number", though NaN is no number anyone wants. Number.isFinite does not convert, so the string "20" fails it, which is what a check wants. Any non-empty string is true, so Boolean("false") is true. And == converts before comparing, so "20" == 20 is true; checks use ===.

Answering 400 with every problem

The server puts the list into its 400 answer. The error body has the same shape for every failure: a sentence in error, and the list in problems, so that a client can show all of them to a person at once:

validate.js

const units = ["bar", "psi"];
module.exports = function problems(data) {
  const list = [];
  if (typeof data !== "object" || data === null || Array.isArray(data)) return ["the body must be a JSON object"];
  if (typeof data.name !== "string" || data.name.trim() === "") list.push("name must be a non-empty string");
  if (typeof data.value !== "number" || !Number.isFinite(data.value)) list.push("value must be a number");
  else if (data.value < 0 || data.value > 150) list.push("value must be between 0 and 150");
  if (!units.includes(data.unit)) list.push(`unit must be one of: ${units.join(", ")}`);
  return list;
};

app.js

const http = require("http");
const problems = require("./validate");
const server = http.createServer(async (req, res) => {
  const send = (status, data, headers = {}) => {
    res.writeHead(status, { "Content-Type": "application/json", ...headers });
    res.end(JSON.stringify(data));
  };
  let body = "";
  for await (const chunk of req) body += chunk;
  let data;
  try {
    data = JSON.parse(body);
  } catch {
    return send(400, { error: "the body is not valid JSON" });
  }
  const list = problems(data);
  if (list.length) return send(400, { error: "the gauge is not valid", problems: list });
  send(201, data, { Location: `/gauges/${data.name}` });
});
server.listen(3000, async () => {
  for (const body of ['{"name":"","value":"20","unit":"kg"}', "[1, 2]", '{"name":"fan","value":20,"unit":"bar"}']) {
    const r = await fetch("http://localhost:3000/gauges", { method: "POST", headers: { "Content-Type": "application/json" }, body });
    console.log(r.status, await r.text());
  }
  server.close();
});

Terminal: node app.js

400 {"error":"the gauge is not valid","problems":["name must be a non-empty string","value must be a number","unit must be one of: bar, psi"]}
400 {"error":"the gauge is not valid","problems":["the body must be a JSON object"]}
201 {"name":"fan","value":20,"unit":"bar"}

The first body had three problems and was told all three. The array got its one problem. The third body passed and was created, with its address in Location. The parse and the check are two different failures with two different messages, and both are 400: the request must change.

Worked example 5

The yard's API takes readings by POST at /readings. A reading must have a gauge from the list boiler, pump; a value that is a number from 0 to 150; and at, the time, as a date in ISO form. Build the check, and answer 400 with every problem.

What we have: three bodies: a good reading; one with every field wrong; and one that is not JSON at all

What we need: 201 for the good one, a 400 that lists all three problems for the second, and a 400 for the third

The plan: parse inside try, answering 400 from the catch; test the body's kind first; then each field with the tests of the table, including Date.parse for the time; answer 400 with the list, or 201 with a Location

app.js

const http = require("http");
const gauges = ["boiler", "pump"];
function problems(d) {
  if (typeof d !== "object" || d === null || Array.isArray(d)) return ["the body must be a JSON object"];
  const list = [];
  if (!gauges.includes(d.gauge)) list.push(`gauge must be one of: ${gauges.join(", ")}`);
  if (!Number.isFinite(d.value) || d.value < 0 || d.value > 150) list.push("value must be a number from 0 to 150");
  if (typeof d.at !== "string" || Number.isNaN(Date.parse(d.at))) list.push("at must be a date in ISO form");
  return list;
}
const server = http.createServer(async (req, res) => {
  const send = (status, data, headers = {}) => {
    res.writeHead(status, { "Content-Type": "application/json", ...headers });
    res.end(JSON.stringify(data));
  };
  let body = "";
  for await (const chunk of req) body += chunk;
  let data;
  try {
    data = JSON.parse(body);
  } catch {
    return send(400, { error: "the body is not valid JSON" });
  }
  const list = problems(data);
  if (list.length) return send(400, { error: "the reading is not valid", problems: list });
  send(201, data, { Location: "/readings/1" });
});
server.listen(3000, async () => {
  const bodies = [
    '{"gauge":"boiler","value":95,"at":"2026-11-09T06:30:00.000Z"}',
    '{"gauge":"fan","value":"95","at":"yesterday"}',
    "gauge=boiler",
  ];
  for (const body of bodies) {
    const r = await fetch("http://localhost:3000/readings", { method: "POST", headers: { "Content-Type": "application/json" }, body });
    console.log(r.status, await r.text());
  }
  server.close();
});

Terminal: node app.js

201 {"gauge":"boiler","value":95,"at":"2026-11-09T06:30:00.000Z"}
400 {"error":"the reading is not valid","problems":["gauge must be one of: boiler, pump","value must be a number from 0 to 150","at must be a date in ISO form"]}
400 {"error":"the body is not valid JSON"}
  1. Date.parse gives NaN for text that is not a date, so the test is Number.isNaN(Date.parse(d.at)); typeof is tested first, because Date.parse of a number is no error.
  2. Number.isFinite(d.value) is false for the string "95", so a string value fails without being converted.
  3. The body gauge=boiler is a form, not JSON; JSON.parse throws, and the catch answers 400 before any check runs.

201 for the good reading, 400 with three problems for the second body, and 400 for the body that was not JSON.

Check: Count the problems of the second body: a gauge not in the list, a value that is a string, and a time that is no date: three, and three were reported.

A path that fails: checking with if (!d.value) for the value. A reading of 0 is a valid number, and !0 is true, so a true reading of zero would be refused as missing.

When you are stuck: A check passes data that is wrong

typeof null is "object": test null by name, and arrays with Array.isArray.

== converts; use === and typeof. Number("") is 0, so do not convert a value before testing its type.

Does a false, 0 or empty string count as missing? Test the type, not the truth of the value.

Your turn

JSON.parse accepted the body. Why does the server still check it?Tap to reveal
  1. What does JSON.parse know about a gauge?

JSON.parse checks the form only; the check tests what the data holds.

What does typeof null give, and what does that mean for a check?Tap to reveal
  1. It is a known slip of the language.

It gives "object", so a check for an object must also test x !== null.

node -p 'Number.isFinite("20") + " " + Number.isFinite(20)'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
false true
  1. Number.isFinite does not convert.
  2. A string is never a finite number to it; 20 is.

It prints false true.

Did you know?

Date.parse is sure of one format

Date.parse is reliable for only one kind of text. MDN says it must support the date time string format that toISOString produces, while other formats are implementation-defined and may not work across all browsers. MDN even names the unreliability of Date.parse as one reason for the new Temporal API. So an API asks for ISO text, and nothing else.

Why it fits here: It answers this topic's question: only ISO text is sure to parse the same everywhere, so APIs accept dates in it alone.

Sources: MDN: Date.parse(); ECMAScript Language Specification: Date.parse

Checks written as data

Checks like these can be written as data instead of code. JSON Schema describes itself as a declarative language for defining structure and constraints for JSON data: a schema such as { "type": "number" } says what a value must be, and a validator checks a body against it. Its site says it is supported by many languages, libraries and frameworks.

Why it fits here: It adds to this topic's checks: JSON Schema writes them down as data, which validators in many languages can apply.

Sources: JSON Schema: What is JSON Schema?; JSON Schema

In one line

A server checks every body after parsing it: the kind of the whole body first, then each field with typeof, Number.isFinite, includes and Date.parse; it collects every problem into a list and answers 400 with all of them.

Shapes of data that age well

At a glance

The shape of an API's JSON is a promise, and clients are built on it. A good shape still makes sense years later.

Use one style of names, in whole words. Send ids as strings, times as ISO text in UTC, and money as whole paise with a currency. Send states as words from a fixed list, and lists inside an envelope with data, total and next. When a value is unknown, leave the field out, and keep null for an answer of none. Each of these habits saves a client from guessing.

Take a guess: What is the rupee's code in the world's list of currencies?

The shape of an API's JSON is its set of names and kinds: which fields an object has, what each holds, how lists are sent. A shape is a promise. Once a client is written against it, every change breaks something somewhere, so a shape is designed with care, once, to last for years. These are the habits that make one last.

Names

HabitDoNot
one style of namecreatedAt, gaugeIdcreated_at in one place and CreatedAt in another
whole wordsvalue, temperatureval, tmp
the same name for the same thing everywhereid on every objectgaugeId here and gauge_no there
a word for a state, not a set of booleans"status": "high""isHigh": true, "isLow": false
a plural for a listreadings: [...]readingList

A reader of the API should be able to guess a name before looking it up. That is what one style and whole words buy.

Dates and times: ISO text, in UTC

JSON has no date kind, so a time travels as text, and the one text that every language reads the same is the ISO form: 2026-11-09T06:30:00.000Z, the date, a T, the time, and Z for UTC. A date written as 09/11/2026 is 9 November in India and 11 September in the United States, so it is never sent.

app.js

const sent = "2026-11-09T06:30:00.000Z";
const at = new Date(sent);
console.log(at.toISOString() === sent, at.getTime());
console.log(new Date("2026-11-09T12:00:00+05:30").toISOString());
console.log(new Date("2026-11-09T06:30:00.000Z") < new Date("2026-11-09T07:15:00.000Z"));
console.log(JSON.stringify({ at }));

Terminal: node app.js

true 1794205800000
2026-11-09T06:30:00.000Z
true
{"at":"2026-11-09T06:30:00.000Z"}

toISOString writes the form, and new Date reads it back exactly: the first line's true. The number beside it is the time as milliseconds since 1970, which is what a Date holds inside. A time sent with an offset, +05:30 for India, is converted to UTC on the way in; noon in India is 06:30 in UTC. Two Dates compare with < as numbers, and JSON.stringify writes a Date in the ISO form by itself.

Money: whole paise, never floating point

app.js

console.log(0.1 + 0.2, 1.15 * 100);
const paise = 1999 * 3;
console.log(paise, (paise / 100).toFixed(2));
console.log(JSON.stringify({ price: { amount: 5997, currency: "INR" } }));
const rupees = (p) => "₹" + (p / 100).toLocaleString("en-IN", { minimumFractionDigits: 2 });
console.log(rupees(16632000), rupees(5997));

Terminal: node app.js

0.30000000000000004 114.99999999999999
5997 59.97
{"price":{"amount":5997,"currency":"INR"}}
₹1,66,320.00 ₹59.97

Floating point numbers cannot hold most decimal fractions exactly: 0.1 + 0.2 is not 0.3, and 1.15 × 100 is not 115. Money counted in rupees with decimals drifts by a paisa here and there, and a paisa in a bank is a bug. So an API sends money as a whole number of the smallest unit, paise, with its currency beside it, and only the screen turns 5997 into ₹59.97. toLocaleString with en-IN writes the Indian groups: 1,66,320.00.

null and a missing field

app.js

const a = JSON.parse('{"name":"fan","note":null}');
const b = JSON.parse('{"name":"fan"}');
console.log("note" in a, a.note, "note" in b, b.note);
console.log(a.note ?? "no note", b.note ?? "no note");

Terminal: node app.js

true null false undefined
no note no note

A field set to null says: there is no note, on purpose. A field that is absent says: nothing was said about it. The in operator tells them apart; the ?? operator treats them the same. An API decides which it means and writes it down. The common habit is to leave out what is unknown, and to send null only where "none" is itself an answer, such as a next page that does not exist.

Lists in an envelope

A list is sent inside an object, called an envelope, and not as a bare array. The envelope carries the list in data, and beside it the total and the address of the next page. A bare array could never grow those fields later:

app.js

const readings = [{ id: "r1", value: 95 }, { id: "r2", value: 96 }, { id: "r3", value: 97 }];
function page(after, limit) {
  const start = after ? readings.findIndex((r) => r.id === after) + 1 : 0;
  const data = readings.slice(start, start + limit);
  const more = start + limit < readings.length;
  return { data, total: readings.length, next: more ? `/readings?after=${data[data.length - 1].id}&limit=${limit}` : null };
}
console.log(JSON.stringify(page(undefined, 2)));
console.log(JSON.stringify(page("r2", 2)));

Terminal: node app.js

{"data":[{"id":"r1","value":95},{"id":"r2","value":96}],"total":3,"next":"/readings?after=r2&limit=2"}
{"data":[{"id":"r3","value":97}],"total":3,"next":null}

The page is asked for by the id of the last item seen, after=r2, and not by a page number. If a reading is added while a client is turning pages, page numbers shift and an item is seen twice or skipped; an id does not shift. The last page's next is null, which is one of the places where null is the answer.

Kind of valueSend it asExample
an ida string"id": "7"
a timeISO text in UTC"at": "2026-11-09T06:30:00.000Z"
moneywhole minor units, with a currency"price": { "amount": 5997, "currency": "INR" }
a stateone word from a fixed list"status": "high"
a listan envelope with data, total and next{ "data": [...], "total": 3, "next": null }
something unknownleave the field outno note field

Worked example 6

The gauge program hands over a raw reading: { id: 7, gauge: "boiler", reading: 95.5, takenAt: a Date, pricePaise: 5997 }. Shape it for the yard's API.

What we have: a raw object with a number id, a gauge name, a reading, a Date and a price in paise

What we need: the API's JSON for one reading, following every habit of this section

The plan: turn the id into a string and the gauge into an object with its id and name. Rename reading to value and add its unit. Derive a status word, write the time in ISO form, and put the price in an object with its currency

app.js

const raw = { id: 7, gauge: "boiler", reading: 95.5, takenAt: new Date(Date.UTC(2026, 10, 9, 6, 30)), pricePaise: 5997 };
const names = { boiler: "Boiler 1", pump: "Pump 2" };
function toApi(r) {
  return {
    id: String(r.id),
    gauge: { id: r.gauge, name: names[r.gauge] },
    value: r.reading,
    unit: "psi",
    status: r.reading > 90 ? "high" : "ok",
    at: r.takenAt.toISOString(),
    price: { amount: r.pricePaise, currency: "INR" },
  };
}
console.log(JSON.stringify(toApi(raw), null, 2));

Terminal: node app.js

{
  "id": "7",
  "gauge": {
    "id": "boiler",
    "name": "Boiler 1"
  },
  "value": 95.5,
  "unit": "psi",
  "status": "high",
  "at": "2026-11-09T06:30:00.000Z",
  "price": {
    "amount": 5997,
    "currency": "INR"
  }
}
  1. String(r.id) keeps the id exact however large it grows, as part 4 showed.
  2. The gauge became an object, so that a client gets its name without a second request, and a new field about gauges has a place to go.
  3. The status is derived from the reading by the server's rule, so that no client has to know the limit of 90.
  4. The price keeps its whole paise and names its currency; the screen will format it.

The API's reading: an id as a string, a gauge object, value with unit, a status word, an ISO time, and a price with its currency.

Check: Walk the table of kinds above against the output: each of its six rows is followed.

A path that fails: sending takenAt as r.takenAt.toString(). That gives a text such as Mon Nov 09 2026 12:00:00 GMT+0530, which depends on the server's time zone and language, and which other languages cannot read reliably.

When you are stuck: Which shape?

A time: ISO text in UTC. Money: whole paise with a currency. An id: a string.

A state: one word from a fixed list, not a set of booleans. A list: an envelope with data, total and next.

Unknown: leave the field out; null only where none is itself an answer.

Your turn

Why does an API send ₹59.97 as 5997?Tap to reveal
  1. Think of 0.1 + 0.2.

Floating point numbers drift; whole paise are exact.

What is the one form for a time in JSON?Tap to reveal
  1. Letters T and Z are in it.

The ISO form in UTC: 2026-11-09T06:30:00.000Z.

node -p '(1999 * 3) / 100'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
59.97
  1. 1999 × 3 is 5997, a whole number, exact.
  2. Dividing by 100 at the end gives 59.97 for the screen.

It prints 59.97.

Did you know?

INR, 356 and 2

The rupee has an international code. In the list of ISO 4217, the standard for currencies, India's rupee is INR, with the number 356 and 2 digits after the decimal point, which is why money can travel as whole paise. Wikipedia explains the letters: IN is India's two-letter country code, and R is the initial of the currency. The same list shows Bhutan using INR too.

Why it fits here: It answers this topic's question: the rupee is INR, number 356, with 2 decimal digits, so 100 paise make a rupee.

Sources: SIX: ISO 4217 currency code list; Wikipedia: ISO 4217

The Tolerant Reader

Martin Fowler named a habit that keeps clients alive when shapes grow: the Tolerant Reader, in May 2011. His advice is to be as tolerant as possible when reading data from a service: take only the parts you need and ignore the rest. Then a new field, which he says should not be a breaking change for anyone, breaks no reader.

Why it fits here: It adds the client's side of this topic's shapes: a reader that ignores unknown fields survives a shape that grows.

Source: Martin Fowler: Tolerant Reader

In one line

A shape is a promise. Use one style of whole-word names, ids as strings, times as ISO text in UTC, and money as whole paise with a currency. Send states as words and lists in an envelope with data, total and next. Leave unknown fields out.

Where it is used

JSON is the common tongue of programs. Here is where each idea of this lesson does its work.

What you learnedWhere it is usedA real example
the JSON formatalmost every web API, and most settings filespackage.json, which npm reads for every project
JSON.stringify and its optionslogs, files, and every API answera server writing its log as one JSON object per line
JSON.parse and the reviverevery API client, and settings filesa client turning the API's ISO times back into Dates
large ids as stringspayments, social networks, databasesa tweet's id, which is sent as a string because it is too large for a number
Content-Type and 415every server that takes a bodya payment API refusing a form body where it wants JSON
checking a bodyevery endpoint that writes dataa sign-up form's API answering every problem at once
shapes that age wellthe design of every APIa shop's API sending prices as whole paise with INR

In the Couriers' Yard, JSON is the label on every parcel, written so that any courier in any town can read it: the same words in the same order, every time.

Mistakes and debugging

These are the slips that people meet most often with JSON. Every output below is the real one, from the code shown.

1. JSON.parse given an object

app.js

const data = { name: "fan" };
try {
  JSON.parse(data);
} catch (e) {
  console.log(e.name, "parsing", String(data));
}
console.log(JSON.parse(JSON.stringify(data)));

Terminal: node app.js

SyntaxError parsing [object Object]
{ name: 'fan' }

JSON.parse takes text. Given an object, it turns the object into text first, and that text is [object Object], which is not JSON. The fix: parse only text; data that is already an object needs no parsing. A copy is made with JSON.parse(JSON.stringify(data)), or better with structuredClone.

2. A body sent without JSON.stringify

app.js

const http = require("http");
const server = http.createServer(async (req, res) => {
  let body = "";
  for await (const chunk of req) body += chunk;
  try {
    JSON.parse(body);
    res.end("parsed");
  } catch (e) {
    res.end(`${e.name}: the body was ${body}`);
  }
});
server.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/gauges", { method: "POST", body: { name: "fan" } });
  console.log(await r.text());
  server.close();
});

Terminal: node app.js

SyntaxError: the body was [object Object]

fetch turned the object into its text, and the server got no data. The fix: body: JSON.stringify(data), with "Content-Type": "application/json" in the headers.

3. A body read twice

app.js

const http = require("http");
const server = http.createServer((req, res) => {
  res.end('{"value":95}');
});
server.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/gauges/boiler");
  console.log(await r.text());
  try {
    console.log(await r.json());
  } catch (e) {
    console.log(e.name, e.message);
  }
  server.close();
});

Terminal: node app.js

{"value":95}
TypeError Body is unusable: Body has already been read

text() read the body, and json() found it used. The fix: read once. When both the text and the data are wanted, read the text and call JSON.parse on it.

4. Money in floating point

app.js

const price = 1.15;
console.log(price * 100, Math.round(price * 100));
const paise = 115;
console.log(paise * 3, (paise * 3) / 100);

Terminal: node app.js

114.99999999999999 115
345 3.45

1.15 × 100 is not 115 in floating point, and a sum of such prices drifts. The fix: count in whole paise, as the second line does, and divide by 100 only for the screen.

5. Dates compared with ===

app.js

const a = new Date("2026-11-09T06:30:00Z");
const b = new Date("2026-11-09T06:30:00Z");
console.log(a === b, a.getTime() === b.getTime(), +a === +b);

Terminal: node app.js

false true true

Two Dates are two objects, and === asks whether they are the same object. The fix: compare their times, with getTime() or a plus sign, which turns a Date into its number.

The debugging corner: print the text

When JSON goes wrong, print the exact text on both sides: on the client, JSON.stringify(body) before sending; on the server, JSON.stringify(body) of what arrived, which shows every quote and every hidden character. The two texts should be the same, and the first difference is the bug.

Quick card

The whole lesson on one card. Come back to it whenever you need a reminder.

app.js

const http = require("http");
const isJSON = (t = "") => t.split(";")[0].trim().toLowerCase() === "application/json";
const problems = (d) => {
  if (typeof d !== "object" || d === null || Array.isArray(d)) return ["the body must be a JSON object"];
  const list = [];
  if (typeof d.name !== "string" || !d.name) list.push("name must be a non-empty string");
  if (!Number.isFinite(d.value)) list.push("value must be a number");
  return list;
};
const server = http.createServer(async (req, res) => {
  const send = (status, data, headers = {}) => {
    res.writeHead(status, { "Content-Type": "application/json", ...headers });   // every answer is JSON
    res.end(JSON.stringify(data));
  };
  if (!isJSON(req.headers["content-type"])) return send(415, { error: "send JSON" });   // the wrong kind of body
  let body = "";
  for await (const chunk of req) body += chunk;
  let data;
  try {
    data = JSON.parse(body);
  } catch {
    return send(400, { error: "not valid JSON" });                                   // not JSON at all
  }
  const list = problems(data);
  if (list.length) return send(400, { error: "not valid", problems: list });         // every problem at once
  send(201, { id: "7", ...data, at: new Date(0).toISOString() }, { Location: "/gauges/7" });   // made, and where
});
server.listen(3000, async () => {
  const tries = [["text/plain", "{}"], ["application/json", "{"], ["application/json", '{"name":"fan","value":20}']];
  for (const [type, body] of tries) {
    const r = await fetch("http://localhost:3000/gauges", { method: "POST", headers: { "Content-Type": type }, body });
    console.log(r.status, await r.text());
  }
  server.close();
});

Terminal: node app.js

415 {"error":"send JSON"}
400 {"error":"not valid JSON"}
201 {"id":"7","name":"fan","value":20,"at":"1970-01-01T00:00:00.000Z"}
When you seeIt meansDo
SyntaxError from JSON.parsethe text is not JSONprint it with JSON.stringify; check quotes, last commas, comments
[object Object] in a bodyan object was sent without JSON.stringifystringify the body and label it application/json
415the body's kind is wrongsend JSON, with Content-Type: application/json
400 with a problems listthe data failed the checkfix every problem, then send again
a Date that is a stringJSON has no date kinda reviver, or new Date where it is used
an id one less than senta number above Number.MAX_SAFE_INTEGERsend ids as strings
₹0.30000000000000004money in floating pointwhole paise, with a currency
Body is unusablea body read twiceread once, keep the result

The story: Parcels that open the same

You learn the yard's packing. A parcel may hold only six kinds of thing: words, numbers, yes or no, nothing, lists and labelled boxes. Every label is written in double quotes. Anything that cannot travel stays behind, and times travel as plain text that the other end turns back into times.

At the yard's door, a checker opens every parcel that arrives. A parcel packed wrongly goes back at once, with a list of everything that was wrong with it.

The Clock Tower's next parcel opens in the Engine Hall exactly as it was packed. "Tomorrow," says the Yardmaster, "the yard's own sorting machine."

Reagents gathered: JSON, JSON.stringify, JSON.parse, reviver, validation, Content-Type.

Sources