16

I have two JSON rows in a PostgreSQL 9.4 table:

      the_column      
----------------------
 {"evens": [2, 4, 6]}
 {"odds": [1, 3, 5]}

I want to combine all of the rows into one JSON object. (It should work for any number of rows.)

Desired output:

{"evens": [2, 4, 6], "odds": [1, 3, 5]}

0

2 Answers 2

26

Use json_agg() to build an array of objects:

SELECT json_agg(the_column) AS result
FROM   tbl;

Or json_each() in a LATERAL join and json_object_agg() to build an object with unnested key/value pairs (your desired output):

SELECT json_object_agg(key, value) AS the_column
FROM   tbl, json_each(the_column);

fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

(For clarity, note that in his answer, data is a json column in the table tbl. - If it's a jsonb column, remember to use jsonb_each.)
20

FYI, if someone's using jsonb in >= 9.5 and they only care about top-level elements being merged without duplicate keys, then it's as easy as using the || operator:

select '{"evens": [2, 4, 6]}'::jsonb || '{"odds": [1, 3, 5]}'::jsonb;
            ?column?                 
-----------------------------------------
{"odds": [1, 3, 5], "evens": [2, 4, 6]}
(1 row)

1 Comment

This is combining columns, not rows.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.