2

I'm looking to create single JSON object per grouped field, and trying to use json_build_object for that purpose. However, the return result is multiple json values instead.

Below is the code

with t(product, key, value) as 
(
    values 
    ('A','category', 'food'),
    ('A','price', '4.00'),
    ('B','category', 'book'),
    ('B','price', '20.00'),
    ('B','genre', 'Sci-Fi')
)
select product, json_build_object(key, value) from t
group by product, key, value

and the result received is

"A" | "{""price"" : ""4.00""}"
"A" | "{""category"" : ""food""}"
"B" | "{""genre"" : ""Sci-Fi""}"
"B" | "{""category"" : ""book""}"
"B" | "{""price"" : ""20.00""}"

What I want as result is

"A" | "{ 'price' : 4.00, 'category': 'food' }"
"B" | "{ 'genre' : 'Sci-Fi', 'category': 'book', 'price': 20.00 }"

2 Answers 2

2

That's what jsonb_object_agg() is for:

select product, jsonb_object_agg(key, value) 
from t
group by product

Online example

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

Comments

2

You can also do it with json_object and array_agg:

with t(product, key, value) as 
(
    values 
    ('A','category', 'food'),
    ('A','price', '4.00'),
    ('B','category', 'book'),
    ('B','price', '20.00'),
    ('B','genre', 'Sci-Fi')
)
select product, json_object(array_agg(key), array_agg(value)) from t
group by product;

 product |                       json_object                        
---------+-----------------------------------------------------------
 A       | {"price": "4.00", "category": "food"}
 B       | {"genre": "Sci-Fi", "price": "20.00", "category": "book"}
(2 rows)

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.