'Using json_build_object

I'm trying to use json_build_object to return JSON formatted SQL response, using the following query:

SELECT json_build_object(
        'id', p.id,
        'description', p.description,
        'discounted_price', p.discounted_price,
        'items', jsonb_agg((i.id, i.price, i.title))
        )
FROM promotion_stores AS ps
                            INNER JOIN promotions AS p ON p.id = ps.promotion_id
                            INNER JOIN promotion_items AS pi ON p.id = pi.promotion_id
                            INNER JOIN items AS i ON pi.item_code = i.item_code
WHERE ps.site_id = ${site}
                     and ps.external_store_id = ${branch}
GROUP BY p.id
LIMIT ${limit}`;

The issue is, that the result look like this:

enter image description here

  1. Not sure what are those f1/f2/f3 fields I see
  2. The object are wrapped with json_build_object key - I don't need it

Any idea how I can fix it? The ideal response should look like this:

promotions: [{id: 1, description: "some desc", items: [] }, { id: 2... }


Solution 1:[1]

A rough draft using some dummy data:

select 
    json_build_object('promotions', jsonb_build_object('one', 1, 'two', 2), 'items', ARRAY[1, 2]) AS json_test;

json_test                        
--------------------------------------------------------
 {"promotions" : {"one": 1, "two": 2}, "items" : [1,2]}


This should serve as starting point.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adrian Klaver