3

I want to combine the following JSON from multiple rows into one single JSON object as a row.

{"Salary": ""}
{"what is your name?": ""}
{"what is your lastname": ""}

Expected output

{
  "Salary": "",
  "what is your name?": "",
  "what is your lastname": ""
}
1
  • 4
    Please do not post sample data as images. You will get more help if you provide sample data as formatted text as shown here or even better as a little SQL script with create table and the insert into statements. Commented Jul 29, 2019 at 8:25

1 Answer 1

19

With only built-in functions, you need to expand the rows into key/value pairs and aggregate that back into a single JSON value:

select jsonb_object_agg(t.k, t.v)
from the_table, jsonb_each(ob) as t(k,v);

If your column is of type json rather than jsonb you need to cast it:

select jsonb_object_agg(t.k, t.v)
from the_table, jsonb_each(ob::jsonb) as t(k,v);

A slightly more elegant solution is to define a new aggregate that does that:

CREATE AGGREGATE jsonb_combine(jsonb) 
(
    SFUNC = jsonb_concat(jsonb, jsonb),
    STYPE = jsonb
);

Then you can aggregate the values directly:

select jsonb_combine(ob)
from the_table;

(Again you need to cast your column if it's json rather than jsonb)

Online example

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

1 Comment

This should be first in a google search, I had to look for 10 other links before I found this simple solution. Thank you very much, you probably saved me 3-4 hours of refactoring :)

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.