Home > database >  Convert rows into json object in postgresql
Convert rows into json object in postgresql

Time:07-08

With PostgreSQL 13 I'm trying to convert rows with 2 columns into a JSON object where a column value is the key and the other column is the value.
My table:

key      | value  
-------- | -------- 
key1     | value1           
key2     | value2        
key3     | value3  

My expected result:
{"key1":"value1","key2":"value2","key3":"value3"}

I found the json_object function on postgresql website : PostgreSQL JSON functions but I can't get it to work.

I tried with other functions:

SELECT jsonb_agg(jsonb_build_object(key ,value))
FROM mytable

but it gives me an array of json objects
[{"key1":"value1"},{"key2":"value2"},{"key3":"value3"}]

I know I can still build it with string functions but I feel like it's an easy task even if I can't get it :-/

Any help would be appreciated !

CodePudding user response:

You can use jsonb_object_agg()

select jsonb_object_agg(key, value)
from the_table
  • Related