4

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 !

1 Answer 1

5

You can use jsonb_object_agg()

select jsonb_object_agg(key, value)
from the_table
Sign up to request clarification or add additional context in comments.

Comments

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.