Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL json_build_object: A How-To Guide

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

json_build_object() is a PostgreSQL function that builds a JSON object from a list of alternating keys and values. You call it as json_build_object('key1', value1, 'key2', value2, ...) and it returns a single JSON object. It is the fastest way to turn relational columns into JSON without string concatenation, and it works in any PostgreSQL version from 9.4 onward. You need nothing beyond a working PostgreSQL connection and a query window (psql, pgAdmin, DBeaver, or any SQL client).

What You'll Need

  • A PostgreSQL server running version 9.4 or later (json_build_object was added in 9.4; jsonb_build_object in the same release).
  • A SQL client or the psql command line, connected to a database where you can run SELECT statements.
  • Optional: a table with columns you want to convert to JSON. The examples below use a simple customers table, but you can test the function with literals alone.

Step-by-Step

  1. Confirm your PostgreSQL version. Run SELECT version(); or SHOW server_version;. If the output shows 9.4 or higher, json_build_object is available. On older servers the function does not exist and you will get a "function does not exist" error.
  2. Test with literals first. Run SELECT json_build_object('name', 'Ada', 'age', 36);. The result is {"name" : "Ada", "age" : 36}. Note that keys must be text and values can be any type PostgreSQL can convert to JSON: numbers, booleans, text, dates, arrays, and even other JSON values.
  3. Build an object from table columns. With a table customers(id, first_name, last_name, email), run:
    SELECT json_build_object('id', id, 'name', first_name || ' ' || last_name, 'email', email) FROM customers;
    Each row returns one JSON object. The column order in the output follows the order of the arguments, not the table definition.
  4. Nest objects for related data. You can pass the result of another json_build_object as a value:
    SELECT json_build_object('customer', json_build_object('id', id, 'email', email), 'active', true) FROM customers;
    Nesting is how you produce structured documents instead of flat key-value pairs.
  5. Aggregate rows into a JSON array. Combine json_build_object with json_agg or jsonb_agg:
    SELECT json_agg(json_build_object('id', id, 'email', email)) FROM customers;
    This returns a single JSON array containing one object per row. Add ORDER BY inside the aggregate if the order matters.
  6. Choose json or jsonb deliberately. json_build_object returns json, which preserves whitespace and key order but is slower to query. jsonb_build_object returns jsonb, which is stored in a binary format, supports indexing, and removes duplicate keys (last one wins). Use jsonb for anything you will filter or index; use json for exact textual output.
  7. Handle NULLs explicitly. If a value is NULL, the key is still present with a JSON null: json_build_object('email', NULL) returns {"email" : null}. If you want to omit the key entirely, use jsonb_strip_nulls on the result, or build the object conditionally with a CASE expression.
  8. Cast keys to text when needed. Keys must be text. Passing an integer key raises an error. Wrap non-text keys in ::text, for example json_build_object(id::text, email).
  9. Verify the output type. Run SELECT pg_typeof(json_build_object('a', 1)); to confirm you are getting json and not jsonb. This matters when you later apply operators such as ->> or @>, which behave differently on the two types.

Common Mistakes

  • Passing an odd number of arguments. json_build_object requires key/value pairs. Three arguments raise "argument list must have even number of elements". Count your arguments.
  • Using a non-text key. Integer or boolean keys fail. Cast them to text first.
  • Forgetting that duplicate keys collapse in jsonb. jsonb_build_object keeps only the last value for a repeated key, while json keeps both. If you rely on duplicates, use json.
  • Assuming NULL removes the key. It does not; the key appears with a null value. Use jsonb_strip_nulls if you need it gone.
  • Mixing json and jsonb in one expression. Nesting a jsonb value inside json_build_object works, but the result is json; operators that need jsonb will fail. Cast the final result with ::jsonb if needed.
  • Expecting column order. The output order matches your argument order, not the table's column order. If downstream code depends on order, pass arguments in the order you want.

Tips

  • Use jsonb_build_object when the output will be stored in a jsonb column, indexed, or queried with containment operators.
  • Combine with jsonb_agg and ORDER BY to produce deterministic arrays for APIs.
  • Use jsonb_pretty() to format output for debugging; it is for display only, not storage.
  • For large result sets, build the object once per row and aggregate; do not concatenate strings manually.
  • Remember that json_build_object is a scalar function: it runs per row, so it composes naturally with WHERE, GROUP BY, and window functions.

Troubleshooting

If you get "function json_build_object does not exist", check the server version; the function requires PostgreSQL 9.4 or later. If you get "argument list must have even number of elements", you passed an odd count of arguments. If a key is rejected, cast it to text. If the output looks wrong because keys are missing, remember that jsonb removes duplicates and that NULL values remain as null. If downstream queries fail on the result, check whether you produced json or jsonb with pg_typeof and cast accordingly. If aggregation returns null, the source table may be empty; json_agg over zero rows returns NULL, so wrap with COALESCE if you need an empty array.

Frequently Asked Questions

What is the difference between json_build_object and jsonb_build_object?

They take the same arguments. json_build_object returns the text-preserving json type; jsonb_build_object returns the binary jsonb type, which supports indexing and removes duplicate keys.

Can I use json_build_object with a subquery?

Yes. Any scalar subquery that returns one value can be passed as a value, for example json_build_object('total', (SELECT count(*) FROM orders)).

Does json_build_object preserve key order?

For the json type, yes, keys appear in argument order. For jsonb, key order is not guaranteed because the binary format sorts keys.

How do I remove null keys from the result?

Wrap the object in jsonb_strip_nulls, for example jsonb_strip_nulls(jsonb_build_object('a', NULL, 'b', 1)), which returns {"b": 1}.

Can I build an array of objects in one query?

Yes, use json_agg or jsonb_agg around json_build_object, optionally with ORDER BY inside the aggregate.

Is json_build_object available in all PostgreSQL versions?

No. It was introduced in PostgreSQL 9.4. Check with SHOW server_version; before relying on it.