4

With this select:

json_agg(json_build_object("id", price::money))

I get the resulting value:

[
  {"6" : "$475.00"}, 
  {"6" : "$1,900.00"},
  {"3" : "$3,110.00"},
  {"3" : "$3,110.00"}
]

I would like the data in this format instead:

{
  "6": ["$475.00","$1,900.00"],
  "3": ["$3,110.00","$3,110.00"]
}

When queried on the server or used with jsonb, the IDs are duplicate and only one of the key value pairs make it through.

1

1 Answer 1

6

You should aggregate prices in groups by ids and use the aggregate function json_object_agg(). You have to use a derived table (subquery in the from clause) because aggregates cannot be nested:

select json_object_agg(id, prices)
from (
    select id, json_agg(price::money) as prices
    from my_table
    group by id
    ) s

Working example in rextester.

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

2 Comments

Everything is wrapped in an array:[{"6" : ["$475.00", "$1,900.00"]}, {"3" : ["$3,110.00", "$3,110.00"]}], i'd like it to just be an object: {"6" : ["$475.00", "$1,900.00"], "3" : ["$3,110.00", "$3,110.00"]}
I realized I had formatted my question wrong, I've edited it to reflect that comment. Sorry!

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.