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.
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.
Why it became so popular
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) - number —
42,3.14 - boolean —
trueorfalse - null —
null - 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
- Keys must be in double quotes.
{name: "x"}is wrong,{"name": "x"}is right. - No trailing comma.
[1, 2, 3,]will throw an error. - Only double quotes for strings, never single.
And one rule surprises everyone, so test yourself first:
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:
He popularised the format and put it on json.org.
JSON gets a tiny, formal standard of its own.
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.
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
- Douglas Crockford. “Introducing JSON.” 2001.
- Tim Bray. “The JavaScript Object Notation (JSON) Data Interchange Format (RFC 8259).” 2017.
- Ecma International. “ECMA-404: The JSON Data Interchange Syntax.” 2017.