Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Reading, writing and checking JSON

After this lesson: I can read, write and check JSON.

55 min lesson7 commandsPostgreSQL and PostgREST lab: a database and a REST API in the browser

The format almost every API speaks

JSON (JavaScript Object Notation) is a plain text format for sending data between programs. Almost every web API sends and receives it.

You will read a JSON answer, write a JSON request and check that data is valid before you trust it.

By the end of this lesson

Note

I can read, write and check JSON.

Key words

WordWhat it meansExample
JSONa text format made of objects and arrays
Objectcurly brackets holding named fields{"id": 1}
Arraysquare brackets holding an ordered list[1, 2, 3]
Fieldone name and its value inside an object"year": 2004
Typethe kind of a value: text, number, true or false
Validationchecking data follows the rules before using it

The cells students fill in are left blank in this preview.

JSON has two shapes and six value kinds

An object is curly brackets holding fields. Each field is a name in double quotes, a colon and a value. An array is square brackets holding values in order.

A value is text in double quotes, a number, true or false, null for nothing, an object or an array. Objects and arrays can sit inside each other.

Worked example: the six kinds of value

KindWritten likeExample of a book field
TextDouble quotes"title": "Night Trains"
NumberDigits, no quotes"year": 2011
Booleantrue or false, no quotes"available": true
Nullnull, meaning no value"author": null
ObjectCurly brackets"publisher": {"name": "Tidal Press"}
ArraySquare brackets"tags": ["travel", "rail"]

The cells students fill in are left blank in this preview.

Read JSON in Python

Code: python
import json

text = '{"id": 2, "title": "Rivers of Europe", "available": false}'
book = json.loads(text)
print(book["title"])
print(type(book["available"]))
# Change the title in the text, then press Run again.
print(json.dumps(book))

Parsing turns JSON text into data

JSON arrives as text. Parsing turns it into the program's own lists and dictionaries. In Python json.loads parses and json.dumps turns data back into text.

After parsing, an object is a dictionary, so book["title"] reads one field, and an array is a list.

Make a catalogue and read one book

Run the next two commands to make a books table. Then ask the API for one book. The answer is an array that holds one object, because a request for rows always answers with an array.

Give psql the password

Command
export PGPASSWORD=shop

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

Make the books table

Command
psql -h db -U shop -c "drop table if exists books; create table books (id serial primary key, title text not null, year int not null, available boolean not null default true); insert into books (title, year, available) values ('Maps of the Sea', 1998, true), ('Rivers of Europe', 2004, false), ('Night Trains', 2011, true); notify pgrst, 'reload schema'"

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

Read one book as JSON

Command
curl -s -w "\n" "http://api:3000/books?id=eq.2"

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

Ask for one field only

Command
curl -s -w "\n" "http://api:3000/books?id=eq.2&select=title"

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

A common mistake

Warning

Many people think that if JSON parses, the data is fine. Parsing only proves the text is well formed. {"title": 5, "year": "soon"} is valid JSON and is a nonsense book. Check the fields and their types yourself.

Validate data before you trust it

Validation checks that data follows the rules. For each field ask three things. Is it there? Is it the right type? Is it in range?

Report every problem at once, so a client fixes them in one go. In this lab the database is the last line of defence, and it refuses a bad row with a 400.

Worked example: checks for a book

FieldMust beExample that fails
titlePresent, and text that is not empty{"year": 2004} or {"title": ""}
yearA whole number from 1450 to 2100{"year": "soon"} or {"year": 3000}
availabletrue or false, and may be left out{"available": "yes"}

The cells students fill in are left blank in this preview.

Send text where a number belongs

Command
curl -s -o /dev/null -w "%{http_code}\n" -X POST -H "Content-Type: application/json" -d '{"title":"Tide Tables","year":"soon"}' "http://api:3000/books"

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

Leave out the title

Command
curl -s -o /dev/null -w "%{http_code}\n" -X POST -H "Content-Type: application/json" -d '{"year":2019}' "http://api:3000/books"

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

Send text that is not JSON at all

Command
curl -s -o /dev/null -w "%{http_code}\n" -X POST -H "Content-Type: application/json" -d 'this is not json' "http://api:3000/books"

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

About this lab and its source: PostgreSQL and PostgREST lab: a database and a REST API in the browser

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.