Tech

What is JSON?

Published
Published:
Table of Contents

JSON is the most common way for programs to send data to each other. Open any website’s developer tools, look at the network tab, and you will see JSON flying around. It started in JavaScript but today every language understands it.

JSON in one breath

JavaScript Object Notation — a lightweight text format for sending structured data. Simple enough for a human to read, strict enough for a computer to never get confused.

It is simple enough for a human to read, and strict enough for a computer to parse quickly without confusion. That balance is the whole secret.

The six things JSON can hold

That is it — only six:

  • string"hello" (always double quotes)
  • number42, 3.14
  • booleantrue or false
  • nullnull
  • object — a set of key and value pairs
  • array — an ordered list

A small example that uses most of them:

{
  "name": "Shravan",
  "browserTabsOpen": 87,
  "isStudent": false,
  "languages": ["C++", "Python", "Julia"],
  "address": {
    "city": "Cambridge",
    "country": "UK"
  },
  "nickname": null
}

Rules that bite beginners

The three classics
  1. Keys must be in double quotes. {name: "x"} is wrong, {"name": "x"} is right.
  2. No trailing comma. [1, 2, 3,] will throw an error.
  3. Only double quotes for strings, never single.

And one rule surprises everyone, so test yourself first:

No. JSON has no comments at all — // and /* */ are both invalid. It is the number-one complaint about JSON, and the single biggest reason config files lean on YAML and TOML instead.

Using it in code

Two operations cover almost everything — read text into data, and write data back to text. Same idea in every language:

A little history

JSON was discovered more than invented — it was always just a slice of JavaScript:

2001
Coined by Douglas Crockford

He popularised the format and put it on json.org.

2013
ECMA-404

JSON gets a tiny, formal standard of its own.

2017
RFC 8259

The current internet standard that APIs rely on today.

These days JSON is pinned down by a formal standard [2]Tim Bray · The JavaScript Object Notation (JSON) Data Interchange Format (RFC 8259) · 2017, so there is no ambiguity left about what is and isn’t valid.

The good thing about reinventing the wheel is that you can get a round one.

Douglas Crockfordon designing JSON

JSON or YAML?

Simple rule: JSON when machines talk to machines, YAML when humans edit the file by hand. If your data is a flat table rather than a tree, CSV may be all you need.

References & further reading

  1. Douglas Crockford. Introducing JSON. 2001.
  2. Tim Bray. The JavaScript Object Notation (JSON) Data Interchange Format (RFC 8259). 2017.
  3. Ecma International. ECMA-404: The JSON Data Interchange Syntax. 2017.
Support this post Sponsor