json and jsonb
a document in a column. ->, ->>, @>, jsonpath, JSON_TABLE, and why jsonb won.
- address
- everything.types.jsonb
- part
- part 6, types and values
- chapter
- chapter 9 of 11
- reading time
- 8 min
json stores the text you gave it; jsonb parses it into a binary tree: keys sorted, duplicates gone, whitespace dropped, and every operator available. use jsonb.
-> gets a value as jsonb, ->> as text, #> follows a path. @> asks "does it contain this", jsonpath (@?, jsonb_path_query) asks anything. a GIN index makes containment fast. and a key you filter on every day is a column that hasn't been promoted yet.
the picture
you know how an API hands you a blob of json, and the fastest thing is to store it as it came? postgres lets you, twice over. json keeps the exact text, like a photocopy. jsonb reads it and files it, like a clerk who retypes the form into a neat card index: tidier, searchable, and the original handwriting is gone.
| type | value | bytes |
|---|---|---|
| json | {"b": 1, "a": 2, "a": 3} | 30 |
| jsonb | {"a": 3, "b": 1} | 44 |
json has to reparse the text for every operation, and it has no equality operator at all (json = json is an error). jsonb has equality, containment, indexing and the rest. the only reasons left for json are keeping duplicate keys or the exact key order, which is a promise the json standard never made anyway.
SELECT '{"a": 1, "b": 2}'::jsonb = '{"b": 2, "a": 1}'::jsonb AS same_object,
'{"price": 1.50}'::jsonb ->> 'price' AS keeps_digits;| same_objectbool | keeps_digitstext |
|---|---|
| t | 1.50 |
(numbers are stored as numeric, so 1.50 stays 1.50.)
getting values out
the events table has a props jsonb column. event 26 is one of the ones with a nested utm object:
SELECT props FROM events WHERE id = 26;| propsjsonb |
|---|
- 1SELECT props -> 'utm' AS result, pg_typeof(props -> 'utm') AS type FROM events WHERE id = 26;
| resultjsonb | typeregtype |
|---|---|
| {"source": "search", "campaign": "spring"} | jsonb |
-> takes a key and gives jsonb back: still json, quotes and all.
@> and @? return a boolean.the type matters as soon as you compare or compute. ->> gives text, so a number has to be cast before arithmetic, and a json null and a missing key both come back as SQL NULL:
SELECT count(*) FILTER (WHERE props -> 'device' IS NULL) AS arrow_null,
count(*) FILTER (WHERE props ->> 'device' IS NULL) AS text_null
FROM events;SELECT count(*) FILTER (WHERE props -> 'device' IS NULL) AS missing_key,
count(*) FILTER (WHERE props -> 'device' = 'null') AS json_null,
count(*) FILTER (WHERE props ->> 'device' IS NULL) AS either
FROM events;| missing_keyint8 | json_nullint8 | eitherint8 |
|---|---|---|
| 749 | 725 | 1474 |
containment and jsonpath
@> is the workhorse: does the left document contain the right one, at any depth? and there's jsonpath, a small query language for json: @? asks whether a path finds anything, jsonb_path_query returns what it finds:
SELECT count(*) FILTER (WHERE props @> '{"utm": {"source": "newsletter"}}') AS contains,
count(*) FILTER (WHERE props @? '$.utm ? (@.source == "newsletter")') AS jsonpath
FROM events;
SELECT jsonb_path_query_array('{"items": [{"sku": "A", "qty": 2}, {"sku": "B", "qty": 5}]}', '$.items[*] ? (@.qty > 3).sku') AS big_orders;| containsint8 | jsonpathint8 |
|---|---|
| 832 | 832 |
| big_ordersjsonb |
|---|
| ["B"] |
GIN indexes both. there are two operator classes, and they trade size for reach. the default, jsonb_ops, indexes every key and every value as separate entries; jsonb_path_ops indexes a hash of each path-to-a-value, which is smaller and more selective but can only answer containment:
- 1SELECT count(*) FROM events WHERE props @> '{"utm": {"source": "newsletter"}}';
| countint8 |
|---|
| 832 |
the default index serves @>.
@> and ?; jsonb_path_ops serves @> and falls back to a seq scan for ?.neither helps props ->> 'device' = 'ios': that's an expression, and it wants an expression index on (props ->> 'device'), or a rewrite to props @> '{"device": "ios"}'. GIN has the inside story, and index types the overview.
building json, and taking it apart
the SQL standard caught up with json in two steps. postgres 16 pg 16+ added the SQL/JSON constructors, JSON_OBJECT, JSON_ARRAY and their aggregates, with standard NULL handling:
SELECT JSON_OBJECT('id': 42, 'name': 'Ada', 'email': NULL) AS with_nulls,
JSON_OBJECT('id': 42, 'email': NULL ABSENT ON NULL) AS absent_on_null,
JSON_ARRAY(1, 'two', NULL, true) AS array_skips_null;| with_nullsjson | absent_on_nulljson | array_skips_nulljson |
|---|---|---|
| {"id" : 42, "name" : "Ada", "email" : null} | {"id" : 42} | [1, "two", true] |
(the older postgres functions, jsonb_build_object and friends, still work and return jsonb.) and postgres 17 pg 17+ added JSON_TABLE, which goes the other way: a path picks the rows, and each column gets a path and a type.
| line | sku | qty | price | gift |
|---|---|---|---|---|
| 1 | KIT-0001 | 2 | 49.00 | f |
| 2 | AUD-0005 | 1 | 129.99 | t |
line numbers the rows, and the missing gift key falls back to its DEFAULT.SELECT jt.*
FROM JSON_TABLE(
'{"order": 1042, "items": [{"sku": "KIT-0001", "qty": 2, "price": 49.00},
{"sku": "AUD-0005", "qty": 1, "price": 129.99, "gift": true}]}',
'$.items[*]'
COLUMNS (line FOR ORDINALITY, sku text PATH '$.sku', qty int PATH '$.qty',
price numeric(10,2) PATH '$.price', gift boolean PATH '$.gift' DEFAULT false ON EMPTY)
) AS jt
ORDER BY jt.line;| lineint4 | skutext | qtyint4 | pricenumeric | giftbool |
|---|---|---|---|---|
| 1 | KIT-0001 | 2 | 49.00 | f |
| 2 | AUD-0005 | 1 | 129.99 | t |
when a key should be a column
jsonb is right for data whose shape you don't control or that varies per row: an API payload, event properties, per-category product attributes. it's wrong for data you query the same way every day. signs that a key wants to be a column:
- it's in a WHERE or a join on every hot query;
- you need a constraint on it (NOT NULL, a foreign key, a CHECK);
- you need statistics on it: the planner has none for a key inside jsonb, so its row estimates are guesses (pg_stats).
the halfway house is a generated column: device text GENERATED ALWAYS AS (props ->> 'device') keeps the document as the source of truth and gives the key a name and a type. a STORED one can be indexed and constrained like any column.
keylines
- jsonb parses and normalises; json keeps the text. use jsonb.
->returns jsonb,->>returns text;#>and#>>take a path.@>and jsonpath (@?) search documents; GIN indexes them, path_ops smaller but containment only.- JSON_OBJECT and JSON_ARRAY are in 16, JSON_TABLE in 17.
- a key you filter, constrain or join on every day wants to be a column.