×

sql · level 3 · unit 7 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

and pull values out of text.

Apps often store events as JSON, text like {"user": "Ava", "basket": {"total": 9}}. Curly brackets hold named values and square brackets hold lists. SQLite can read inside it.

json_extract(body, '$.user') follows a path: $ is the whole thing, .user is a name inside it, and $.basket.total is a name inside a name. body ->> '$.user' does the same, shorter. A missing path gives NULL.

Broken JSON makes both stop with malformed JSON. Real data always has some, so filter with WHERE json_valid(body) first.

SELECT id,
  body ->> '$.user' AS user,
  body ->> '$.action' AS action,
  body ->> '$.basket.total' AS total
FROM events
WHERE json_valid(body)
ORDER BY id;

Event 5 was cut off halfway, so json_valid gives 0 and the row is skipped.