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:
- Not sure what are those f1/f2/f3 fields I see
- The object are wrapped with
json_build_objectkey - 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... }

select jsonb_agg(('one', 'two')); [{"f1": "one", "f2": "two"}], which usesto_jsonbfrom here JSON Operators. So it takes the row and turns it into a object in an array wheref1,f2,f3are keys created by the function.json_build_objectyou see is the 'column' name not the key. I believe your client's presentation is confusing the issue. If you want to change the column name dojson_build_object(...) AS some_alias. Try running the query inpsqlI believe you will see a better picture of what is going on.