AI Hints
Home›PostgreSQL Tutorial›Updating and Building JSON
PostgreSQL · Lesson 44 of 120

Building JSON

Tables to JSON.

⏱ 2 min read▶ Video at 38:18🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

An app's API wants JSON. Postgres can build it straight from your tables, so the database hands back exactly the shape the app needs.

  • API wants JSON
  • Build in SQL
  • Exact shape

A genre with its books

Jsonb build object makes an object from keys and values. Jsonb agg collects rows into a JSON array. Together, they build a genre with a list of its books, and jsonb pretty lays it out. Run it. Ready to send to an app.

query.sqlsql
SELECT jsonb_pretty(jsonb_build_object(
         'genre', genre,
         'books', jsonb_agg(jsonb_build_object('title', title, 'price', price)
                            ORDER BY price DESC)
       )) AS doc
FROM books
WHERE genre = 'Cooking'
GROUP BY genre;
Output
                   doc
------------------------------------------
 {                                       +
     "books": [                          +
         {                               +
             "price": 27.99,             +
             "title": "Spice Roads"      +
         },                              +
         {                               +
             "price": 24.99,             +
             "title": "The Quiet Kitchen"+
         },                              +
         {                               +
             "price": 21.49,             +
             "title": "One Pan Dinners"  +
         }                               +
     ],                                  +
     "genre": "Cooking"                  +
 }
(1 row)

JSON builders

Jsonb build object makes objects. Jsonb build array makes arrays. Jsonb agg collects rows. And to jsonb turns a whole row into an object. Jsonb pretty formats the output for humans.

keyvalue
jsonb_build_objectan object
jsonb_aggrows → array
to_jsonb(row)row → object
jsonb_prettyreadable

Summary

Postgres can build JSON directly, with build object and agg. Next, when to use JSONB, and when to use columns.

Key takeaways
  • jsonb_build_object
  • jsonb_agg
  • API shapes
Next up: JSONB or Columns? — choose wisely