Lesson 1 · Unit 02
JSON shapes
Ids, times, money, null and lists in shapes that survive every client
What you practise
- Consistent names, missing against null, timestamps and time zones, ids as strings, money, envelopes
- A schema as the written contract
Try a question from this lesson
Pick one
A JavaScript client holds every JSON number as a 64-bit float. This simulates it reading one large order id. What does it print?
big = 9007199254740993
as_js = int(float(big))
print(as_js - big)Hint
A double has 53 bits for the digits. This id is 2 to the power 53, plus one.
Correct answer
-1
Why
A double cannot represent 2^53 + 1, so the id silently becomes its even neighbour and now names a different order. Nothing errors. This is why ids travel as strings.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Ids are strings
An id is a name, not a quantity: nobody adds two order ids. Send it as a string and every client keeps it exactly, whatever its number type.
Strings also leave you free to change how ids are made later (longer, with letters, a UUID) without breaking the contract.
{
"id": "9007199254740993",
"customerId": "c_81f3",
"quantity": 2
}Concept
Wrap lists in an object
A reply whose top level is a bare array can never grow: there is nowhere to add a cursor, a count or a warning without changing its type, which breaks every client.
Wrap the list in an object from day one. New members can then be added beside it, and old clients simply ignore them.
{
"data": [
{"id": "41", "total": 1999},
{"id": "42", "total": 500}
],
"next": "42"
}Concept
A schema is the contract, written down
A JSON Schema describes a shape in JSON itself: which members exist, their types, which are required.
Servers validate requests against it, clients generate types from it, and both sides test against it. Members it does not mention are allowed unless it says otherwise.
{
"type": "object",
"required": ["id", "total"],
"properties": {
"id": {"type": "string"},
"total": {"type": "integer"},
"note": {"type": "string"}
}
}9 more exercises in the app
- 4× multiple choice
- 1× true or false
- 2× type the answer
- 1× match the pairs
- 1× fill the blanks
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.