Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine multiple JSON rows into one JSON object in PostgreSQL

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": ""
}
like image 652
Dev Raj Gautam Avatar asked May 18 '26 07:05

Dev Raj Gautam


1 Answers

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


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!