1

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... }
2
  • select jsonb_agg(('one', 'two')); [{"f1": "one", "f2": "two"}], which uses to_jsonb from here JSON Operators. So it takes the row and turns it into a object in an array where f1,f2,f3 are keys created by the function. Commented Feb 21, 2022 at 18:54
  • The json_build_object you 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 do json_build_object(...) AS some_alias. Try running the query in psql I believe you will see a better picture of what is going on. Commented Feb 21, 2022 at 19:04

1 Answer 1

2

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.

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.