PostgreSQL json_build_array: How to Use It
In this article
Use json_build_array() in PostgreSQL to turn a list of SQL values into a JSON array. It takes any number of arguments — zero or more — and returns a single json value where each argument becomes an element in the order you supplied them. For example, SELECT json_build_array('a', 1, true); returns ["a", 1, true]. That is the whole function: no configuration, no setup, no extension. You need a PostgreSQL connection and a version that supports JSON functions (9.3 and later for the core JSON functions; jsonb variants arrived in 9.4).
What You'll Need
- A PostgreSQL database you can run queries against (any recent major version — 12, 13, 14, 15, 16, 17 all include this function).
- A SQL client:
psql, pgAdmin, DBeaver, or any tool that lets you execute SQL. - Permission to run
SELECTstatements on the tables you reference (or just the ability to run a bareSELECT). - Optional: a table with columns you want to convert into arrays; otherwise you can test with literals.
Step-by-Step
- Connect to your database. Open
psqlor your GUI client and connect to the database where you want to run the query. Inpsqlthe command is\c your_database_nameafter connecting, or start withpsql -d your_database_name. - Run a minimal test. Execute
SELECT json_build_array();. It returns[]— an empty JSON array. This confirms the function exists and your client displays JSON output correctly. - Pass literal values. Run
SELECT json_build_array('hello', 42, true, NULL);. You get["hello", 42, true, null]. Note that SQLNULLbecomes JSONnull— it is not omitted. - Mix data types deliberately. The function does not require matching types.
json_build_array(1, '1', 1.0)returns[1, "1", 1.0]— the number, the string, and the numeric literal are preserved as written. If you need consistent types, cast first:json_build_array(1::text, '1'::text). - Build arrays from table columns. Query
SELECT json_build_array(id, name, created_at) FROM users LIMIT 5;. Each row produces one JSON array containing that row's three column values, in the order you listed them. The result column has typejson. - Nest arrays for structure. Because the function accepts any expression, you can nest calls:
SELECT json_build_array('user', json_build_array(id, name)) FROM users;. This yields["user", [1, "Alice"]]. Nesting is the standard way to build small hierarchical shapes withoutjson_build_object. - Aggregate rows into one array. A single
json_build_arraycall handles one row. To collect many rows into one array, combine it withjson_agg:SELECT json_agg(json_build_array(id, name)) FROM users;. The result is a JSON array of arrays, one inner array per row. - Use it inside a larger JSON document. You can pass the result to
json_build_object:SELECT json_build_object('user', json_build_array(id, name)) FROM users;. This produces{"user": [1, "Alice"]}. The two functions are designed to work together. - Check the result type. Run
SELECT pg_typeof(json_build_array(1, 2));. It returnsjson, notjsonb. If you needjsonb, cast the result:json_build_array(1, 2)::jsonb. - Store or return the value. Use the expression directly in a
SELECTfor API responses, or insert it into ajsonorjsonbcolumn:INSERT INTO logs (payload) VALUES (json_build_array('event', now()));. The column type must accept JSON;jsonbcolumns will cast automatically in most cases, but an explicit::jsonbcast is safer.
Common Mistakes
- Expecting
jsonboutput.json_build_arrayreturnsjson. It preserves whitespace and key order, and it does not supportjsonboperators like@>or?without a cast. Cast to::jsonbwhen you need those operators or indexing. - Assuming NULL is skipped. SQL
NULLbecomes JSONnulland stays in the array. If you want to omit nulls, filter withWHERE col IS NOT NULLor usejsonb_strip_nullson ajsonbcast. - Passing a single array argument by accident.
json_build_array(ARRAY[1,2,3])does not flatten the array. It produces[[1,2,3]]— a JSON array containing one element, which is itself a JSON array. Useto_json(ARRAY[1,2,3])if you want[1,2,3]. - Confusing it with
array_to_json.array_to_jsonconverts a PostgreSQL array to JSON.json_build_arraybuilds a JSON array from separate arguments. They are not interchangeable. - Forgetting row context. In a query like
SELECT json_build_array(id, name) FROM users, you get one array per row. If you wanted one array for all rows, you needjson_aggaround it. - Type mismatches in comparisons. Comparing a
jsonresult to ajsonbcolumn can fail or behave unexpectedly. Cast one side explicitly.
Tips
- Order matters. The arguments appear in the array in the exact order you write them, so list columns deliberately.
- Use
json_build_arraywithjson_build_objectto build nested documents without string concatenation. - For large result sets, cast to
jsonbearly if you plan to query inside the JSON —jsonbsupports indexing and containment operators. - Wrap the call in
COALESCEif a column may be NULL and you want a default:json_build_array(COALESCE(name, 'unknown')). - Use
pg_typeof()to confirm what a function returns when you are unsure — it is faster than guessing.
Troubleshooting
Function does not exist. You are likely on a very old PostgreSQL version (pre-9.3) or connected to a different database than you think. Check with SELECT version(); and confirm the connection.
Output looks like a string. Some clients display JSON as text. That is a display issue, not a data issue. Run SELECT pg_typeof(json_build_array(1)); to confirm the type is json.
Unexpected nested arrays. Check whether you passed an array as a single argument. json_build_array(ARRAY[1,2]) nests; json_build_array(1, 2) does not.
Cannot use ->> or @> on the result. Those operators are for jsonb. Cast: (json_build_array(1,2))::jsonb.
Permission denied. You need SELECT on the underlying tables. Ask your database administrator or run the query against a table you own.
If that did not work, simplify: run SELECT json_build_array(); with no arguments. If that fails, the problem is the connection or version, not your query.
Frequently Asked Questions
What is the difference between json_build_array and jsonb_build_array?
json_build_array returns json; jsonb_build_array returns jsonb. The jsonb version parses the input into a binary format, which supports indexing and containment operators but does not preserve whitespace or key order.
Can json_build_array take zero arguments?
Yes. json_build_array() returns an empty JSON array [].
Does json_build_array handle NULL values?
Yes. SQL NULL becomes JSON null and remains an element in the array. It is not dropped.
How do I build one array from many rows?
Use json_agg around it: SELECT json_agg(json_build_array(id, name)) FROM users;. A bare json_build_array in the select list produces one array per row.
Can I nest json_build_array inside json_build_object?
Yes, and that is a common pattern. json_build_object('items', json_build_array(1,2,3)) produces {"items": [1,2,3]}.
Why does json_build_array(ARRAY[1,2]) return [[1,2]]?
Because the array is one argument, not two. The function treats each argument as a single element. To flatten a PostgreSQL array into a JSON array, use to_json(ARRAY[1,2]) or array_to_json(ARRAY[1,2]).