JSON: how programs talk to each other
What JSON is and why web APIs use it: objects, lists, strings and numbers, reading it with jq and Python, and fixing a broken document.
What JSON is and why web APIs use it: objects, lists, strings and numbers, reading it with jq and Python, and fixing a broken document.
In plain words
JSON is a form with labelled boxes. "name" is the label, "Ada" is what is in the box. Two programs that have never met can read the same form, because the labels and the box rules are the same everywhere.
Try it yourself
With the API from Your first web API with Flask running (python app.py in another terminal), look at its answer:
curl -s "http://localhost:8000/upper?text=hello" | jq .
curl -s "http://localhost:8000/upper?text=hello" | jq .upper
jq is a tool that reads and picks from JSON. Now write some yourself and pick from it:
echo '{"name": "Ada", "days": [1, 2, 3]}' | jq '.days[1]'
python3 -c 'import json; d = json.loads("{\"a\": 1}"); print(d["a"] + 1)'
A step further
JSON has few rules, and they are strict: text in double quotes, labels in double quotes, no comma after the last item, and only these kinds of values: text, number, true, false, null, a list [ ] and an object { }.
Break it on purpose and read the message:
echo '{"a": 1,}' | jq .
The words an API and its users agree on (the labels, the kinds of values) are called a contract. Change a label and every program that reads it breaks.
How it works in real projects
Almost every service we use answers in JSON, from payment providers to AI assistants. A good client checks two things: the status code (did it work?) and the shape of the JSON (is what I need there?).