The JSON Format — API

JSON is a text format for data, with six kinds of value: string (double quotes), number, boolean, null, array [ ] and object { }. Values may nest: arrays and…

Open DevTools (the developer tools built into Chrome) while a website is loading data. Pick the Network tab, click one request, then open the Response tab. Very often it holds text like {"id": 1, "title": "The Rainbow Troops"}. This text format is called JSON (JavaScript Object Notation), and it is used to send data. Almost every web API uses it, the Bookshop API included.

JSON looks like a JavaScript object, but its rules are far stricter. Think of an official form. Every entry has a label that must be written exactly, and if a single mark is wrong, the clerk rejects the whole form. In JSON, one entry is called a field: its label is called the key, and its content is called the value. The clerk is JSON.parse, the JavaScript function that reads JSON text. If a single mark is wrong, JSON.parse rejects the whole text.

Six kinds of value

This is the full body of the answer to GET /books/1 from the Bookshop API:

{
  "id": 1,
  "title": "The Rainbow Troops",
  "price": 89000,
  "in_stock": true,
  "discount": null,
  "tags": ["novel", "education"],
  "author": { "id": 1, "name": "Andrea Hirata" }
}
Kind Example Note
string "The Rainbow Troops" always double quotes
number 89000, 4.5 no quotes, no thousands separator, a dot for decimals
boolean true, false lowercase
null null empty on purpose
array ["novel", "education"] an ordered list, in [ ]
object {"id": 1, "name": "Andrea Hirata"} key and value pairs, in { }

A value may hold other values. tags is an array inside the object, and author is an object inside the object. Data nested like tags and author, one value inside another, is what the exercise asks for.

The rules that make JSON.parse refuse

Before you read the list, guess: is {"title": "The Rainbow Troops", "price": 89000,} valid, or rejected?

So {"title": "The Rainbow Troops", "price": 89000,} is rejected, because of the comma after 89000. Chrome gives its reason like this:

SyntaxError: Expected double-quoted property name in JSON at position 47 (line 1 column 48)

What the message means: after a comma, JSON.parse expects a new key in double quotes. But at position 47 (positions are counted from 0, so this is the 48th character), a } arrives. Firefox and Safari word the message differently, but both refuse it too.

Three more examples that are rejected:

JSON The problem
{name: "Budi", age: 17} keys need quotes
{"name": "Budi", "age": 17,} trailing comma
{"name": 'Budi', "age": 17} a string in single quotes

A JavaScript object isn't JSON

In JavaScript code an object can be written more freely: keys without quotes, single quotes and a trailing comma are all allowed. JSON, on the other hand, is the text sent over the network. Two built-in JavaScript functions connect the two:

const book = { title: 'The Rainbow Troops', price: 89000, discount: undefined };

const text = JSON.stringify(book);
console.log(text); // {"title":"The Rainbow Troops","price":89000}

const back = JSON.parse(text);
console.log(back.price); // 89000

res.json(object) in Express calls JSON.stringify for you. That's why in the exercise you may write keys without quotes: what you write is a JavaScript object, and what gets sent is JSON.

The Content-Type: application/json header

A JSON body is always sent with the header Content-Type: application/json, in requests and responses alike. That header means "this body is JSON, read it by JSON's rules". res.json(...) sets it for you. When a client sends JSON, you have to write that header yourself (covered in the earlier Request & Response lesson).

Exercise: GET /profile

The exercise code has the same shape as this book detail endpoint:

app.get("/books/1", (req, res) => {
  res.json({
    id: 1,
    title: "The Rainbow Troops",
    tags: ["novel", "education"],
    author: { id: 1, name: "Andrea Hirata" },
  });
});

In the exercise the endpoint is GET /profile, and its answer holds name, age, skills (an array of three texts) and address (an object holding city and country).

⚠️ Quotes, commas and numbers that cause trouble

TL;DR: JSON is a text format for data, with six kinds of value: string (double quotes), number, boolean, null, array [ ] and object { }. Values may nest: arrays and objects may hold other values. JSON.parse (the function that reads JSON text) refuses keys (the names of the entries) without quotes, single quotes, a trailing comma, comments, undefined and numbers starting with zero. A JavaScript object isn't JSON: JSON.stringify turns an object into JSON text, JSON.parse turns it back into an object, and res.json in Express calls JSON.stringify for you. A JSON body is sent with the header Content-Type: application/json.

⚡ Six kinds of value, and they nest

Write:

app.get("/books/1", (req, res) => {
  res.json({
    id: 1,
    title: "The Rainbow Troops",
    tags: ["novel", "education"],
    author: { id: 1, name: "Andrea Hirata" },
  });
});

Meaning: res.json sends this object as JSON (a text format for data). JSON has six kinds of value: string, number, boolean, null, array [ ] and object { }. Values can nest: tags is an array inside the object, and author is an object inside the object.

⚡ JSON is stricter than a JavaScript object

Guess first: is {"title": "The Rainbow Troops", "price": 89000,} valid, or rejected?

Rejected, because of the comma after 89000. After a comma, JSON.parse (the function that reads JSON text) expects a new key (the name of an entry) in double quotes, but a } arrives.

Meaning: In JSON, keys and strings need double quotes. There's no trailing comma, no comment and no undefined. So {name: "Budi", age: 17} is rejected: its keys (name and age) have no quotes.

⚡ stringify out, parse back

Write:

const book = { title: 'The Rainbow Troops', price: 89000, discount: undefined };

const text = JSON.stringify(book);
console.log(text); // {"title":"The Rainbow Troops","price":89000}

Meaning: JSON.stringify turns an object into JSON text to send, and a field (an entry) holding undefined, here discount, is dropped. JSON.parse turns that text back into an object. In Express, res.json calls JSON.stringify for you.

What you will learn