Working with JSON

Topic 2 of 4 in Beyond the basics11 min readBeginnerFree course

Overview

Relational tables are great when every row has the same columns. But some data is irregular: a kettle has a voltage, a teapot has a material, a coffee has a roast level and tasting notes. Creating a column for every possible attribute leaves most of them empty. PostgreSQL’s answer is the jsonb type: a column that holds a JSON document, with operators to query inside it, and indexes to make that fast. It gives you some of the flexibility of a document database without leaving SQL.

json and jsonb

PostgreSQL has two JSON types. json stores the text exactly as given; jsonb stores a parsed, binary form — it removes duplicate keys and whitespace, doesn’t keep key order, and supports indexing and many more operators. Use jsonb unless you need the original text byte for byte.

Add a column for product attributes and fill a few:

SQL
ALTER TABLE products ADD COLUMN attrs jsonb;

UPDATE products SET attrs = '{"color": "black", "voltage": 230, "tags": ["gift", "electric"], "dims": {"h": 24, "w": 16}}'
WHERE name = 'Electric Kettle';
UPDATE products SET attrs = '{"color": "silver", "voltage": 230, "tags": ["electric"], "grind_settings": 40}'
WHERE name = 'Burr Grinder';
UPDATE products SET attrs = '{"material": "glass", "capacity_ml": 800, "tags": ["gift"]}'
WHERE name = 'Glass Teapot';
UPDATE products SET attrs = '{"origin": "Ethiopia", "roast": "light", "notes": ["jasmine", "lemon"]}'
WHERE name = 'Ethiopian Yirgacheffe';

SELECT name, attrs FROM products WHERE attrs IS NOT NULL ORDER BY id;
Text
ALTER TABLE
UPDATE 1
UPDATE 1
UPDATE 1
UPDATE 1
         name          |                                            attrs                                             
-----------------------+----------------------------------------------------------------------------------------------
 Ethiopian Yirgacheffe | {"notes": ["jasmine", "lemon"], "roast": "light", "origin": "Ethiopia"}
 Burr Grinder          | {"tags": ["electric"], "color": "silver", "voltage": 230, "grind_settings": 40}
 Electric Kettle       | {"dims": {"h": 24, "w": 16}, "tags": ["gift", "electric"], "color": "black", "voltage": 230}
 Glass Teapot          | {"tags": ["gift"], "material": "glass", "capacity_ml": 800}
(4 rows)

JSON values are written as text in single quotes and checked on the way in — invalid JSON is rejected. Notice that jsonb has reordered the keys (shorter keys first); that’s normal, as JSON objects have no meaningful key order.

Getting values out

Working with jsonb, using a products.attrs document {“color”: “black”, “voltage”: 230, “tags”: [“gift”, “electric”], “dims”: {“h”: 24, “w”: 16}}. attrs -> ‘dims’ returns the jsonb value {“h”: 24, “w”: 16}. attrs ->> ‘color’ returns the text value black. attrs -> ‘dims’ ->> ‘h’ returns 24, nested, as text. attrs #>> ‘{tags,0}’ returns gift, by path. attrs @> ‘{“color”: “black”}’ returns true: contains. attrs ? ‘voltage’ returns true: has key. -> returns jsonb, to keep drilling in; ->> returns text, to compare and display. Cast for numbers: (attrs ->> ‘voltage’)::int. @> and ? can use a GIN index: CREATE INDEX ON products USING gin (attrs). Build JSON from rows with jsonb_build_object() and jsonb_agg(); expand arrays with jsonb_array_elements(). Use jsonb for truly flexible attributes; if every row has the field and you filter on it, a real column is better.

The two key operators look almost the same, and the difference matters:

  • -> returns jsonb — use it to keep drilling into nested objects and arrays;
  • ->> returns text — use it for the final value you want to display or compare.
SQL
SELECT name,
       attrs -> 'dims'             AS dims_json,
       attrs -> 'dims' ->> 'h'     AS height,
       attrs ->> 'color'           AS color,
       attrs -> 'tags' -> 0        AS first_tag_json,
       attrs #>> '{tags,0}'        AS first_tag
FROM products
WHERE name = 'Electric Kettle';
Text
      name       |     dims_json      | height | color | first_tag_json | first_tag 
-----------------+--------------------+--------+-------+----------------+-----------
 Electric Kettle | {"h": 24, "w": 16} | 24     | black | "gift"         | gift
(1 row)

Array positions start at 0 in JSON (unlike SQL strings). #> and #>> take a path as an array of keys and indexes. A missing key simply gives NULL, so the same query works on rows with different shapes:

SQL
SELECT name, attrs ->> 'color' AS color, attrs ->> 'material' AS material
FROM products
WHERE attrs IS NOT NULL
ORDER BY id;
Text
         name          | color  | material 
-----------------------+--------+----------
 Ethiopian Yirgacheffe |        | 
 Burr Grinder          | silver | 
 Electric Kettle       | black  | 
 Glass Teapot          |        | glass
(4 rows)

->> always returns text. To compare numbers, cast: otherwise '230' > '40' is compared alphabetically.

SQL
SELECT name, (attrs ->> 'voltage')::int AS volts
FROM products
WHERE (attrs ->> 'voltage')::int >= 220
ORDER BY name;
Text
      name       | volts 
-----------------+-------
 Burr Grinder    |   230
 Electric Kettle |   230
(2 rows)

Filtering: containment and existence

Two operators make JSON filtering short and fast:

  • a @> b — does document a contain b? Works for nested objects and arrays.
  • a ? 'key' — does a have this key (or, for an array, this string element)?
SQL
SELECT name FROM products WHERE attrs @> '{"tags": ["electric"]}' ORDER BY name;
Text
      name       
-----------------
 Burr Grinder
 Electric Kettle
(2 rows)
SQL
SELECT name FROM products WHERE attrs ? 'material';
Text
     name     
--------------
 Glass Teapot
(1 row)
SQL
SELECT name FROM products WHERE attrs -> 'tags' ? 'gift' ORDER BY name;
Text
      name       
-----------------
 Electric Kettle
 Glass Teapot
(2 rows)

For larger tables, a GIN index makes @> and ? searches fast, however many different keys the documents have:

SQL
CREATE INDEX products_attrs_idx ON products USING gin (attrs);
Text
CREATE INDEX

Changing JSON documents

You can replace a whole document with UPDATE … SET attrs = '…', but usually you want to change one part. || merges objects (keys on the right win), - removes a key, and jsonb_set replaces a value at a path:

SQL
UPDATE products
SET attrs = attrs || '{"warranty_years": 2}'
WHERE name = 'Electric Kettle';

UPDATE products
SET attrs = jsonb_set(attrs, '{dims,h}', '25') - 'color'
WHERE name = 'Electric Kettle';

SELECT attrs FROM products WHERE name = 'Electric Kettle';
Text
UPDATE 1
UPDATE 1
                                              attrs                                              
-------------------------------------------------------------------------------------------------
 {"dims": {"h": 25, "w": 16}, "tags": ["gift", "electric"], "voltage": 230, "warranty_years": 2}
(1 row)

From rows to JSON

Applications and APIs often want JSON back. PostgreSQL can build it directly. jsonb_build_object makes an object from key–value pairs, and jsonb_agg gathers many rows into an array — so a whole nested document can come from one query:

SQL
SELECT jsonb_build_object(
         'order_id', o.id,
         'customer', c.first_name,
         'items', jsonb_agg(jsonb_build_object('product', p.name, 'qty', oi.quantity)
                            ORDER BY p.name)
       ) AS order_json
FROM orders AS o
JOIN customers AS c    ON c.id = o.customer_id
JOIN order_items AS oi ON oi.order_id = o.id
JOIN products AS p     ON p.id = oi.product_id
WHERE o.id = 9
GROUP BY o.id, c.first_name;
Text
                                                            order_json                                                            
----------------------------------------------------------------------------------------------------------------------------------
 {"items": [{"qty": 1, "product": "Electric Kettle"}, {"qty": 1, "product": "Jasmine Green"}], "customer": "Asha", "order_id": 9}
(1 row)

to_jsonb(row) converts a whole row, and jsonb_pretty(…) formats a document for reading.

From JSON to rows

The reverse is just as useful — for example when an API or a file gives you a JSON array. jsonb_array_elements turns an array into rows, and jsonb_to_recordset turns an array of objects into a typed table:

SQL
SELECT p.name, note
FROM products AS p
CROSS JOIN LATERAL jsonb_array_elements_text(p.attrs -> 'notes') AS note
WHERE p.attrs ? 'notes';
Text
         name          |  note   
-----------------------+---------
 Ethiopian Yirgacheffe | jasmine
 Ethiopian Yirgacheffe | lemon
(2 rows)
SQL
SELECT *
FROM jsonb_to_recordset('[{"sku": "MUG-01", "qty": 4, "price": 9.5},
                          {"sku": "TIN-02", "qty": 10, "price": 6}]')
     AS x(sku text, qty int, price numeric);
Text
  sku   | qty | price 
--------+-----+-------
 MUG-01 |   4 |   9.5
 TIN-02 |  10 |     6
(2 rows)

That second query is a handy way to load a JSON payload into a table with INSERT … SELECT. (PostgreSQL 17 added the SQL-standard JSON_TABLE function, which does the same job with richer options, plus JSON_VALUE, JSON_QUERY and JSON_EXISTS.)

When to use JSON — and when not

JSON columns are great for:

  • genuinely variable attributes, like product specifications that differ by category;
  • data you store and return whole, such as API payloads, settings or event logs;
  • nested structures that would otherwise need many small tables.

They’re a poor fit for:

  • fields every row has and that you filter, sort or join on — a real column is smaller, faster, and can have a type and constraints;
  • relationships — a customer id buried inside JSON can’t be a foreign key;
  • anything you need to aggregate heavily, because every access has to dig the value out.

A common, healthy design is a mix: proper columns for the core fields, and a jsonb column for the long tail of optional extras.

Other databases: MySQL has a JSON type with -> and ->> too; SQLite has JSON functions and the same operators; SQL Server stores JSON as text with JSON_VALUE and OPENJSON. PostgreSQL’s jsonb with GIN indexing is among the most capable implementations.

Exercise

Product attributes

Add a jsonb column called attrs to products. Set it for three products with UPDATE statements: the Electric Kettle (id 10) gets {"voltage": 230, "color": "black", "tags": ["gift", "electric"]}, the Burr Grinder (id 9) gets {"voltage": 230, "color": "silver", "tags": ["electric"]} and the Glass Teapot (id 11) gets {"material": "glass", "tags": ["gift"]}. Then return the name and the color (as text) of every product whose tags array contains "gift", sorted by name — the kettle (black) and the teapot (no colour).

SQL
ALTER TABLE products ADD COLUMN attrs jsonb;

-- three UPDATEs, then the query

Summary

  • Use jsonb (binary JSON) rather than json: it's validated, indexable and supports all the operators.
  • -> returns a jsonb value (for drilling further in); ->> returns text; #> and #>> follow a path; cast text to compare as numbers.
  • @> tests whether a document contains another; ? tests whether a key or array element exists — both can use a GIN index.
  • jsonb_build_object and jsonb_agg turn rows into JSON documents; jsonb_array_elements and jsonb_to_recordset turn JSON back into rows.
  • Use JSON for genuinely flexible or nested data; keep fields you filter, join or constrain on in real columns.