0

I have data like:

Name PhoneNumber
Bob {"type":"mobile", "number":"1-234-567-8910"}
Bob {"type":"work", "number":"1-555-555-5555"}
Jane {"type":"mobile", "number":"1-333-333-3333"}

I would like to combine over "Name" to be in a single json array like so:

PhoneNumbers
{"name": "Bob", "PhoneNumbers": [{"type":"mobile", "number":"1-234-567-8910"},{"type":"work", "number":"1-555-555-5555"}]}
{"name": "Jane", "PhoneNumbers": [{"type":"mobile", "number":"1-333-333-3333"}]}

I was looking at json_agg, but I am not sure how to group properly to get the results above.

1 Answer 1

2

Using the JSON functions:

SELECT jsonb_build_object(
          'name',
          name,
          'PhoneNumbers',
          jsonb_agg(phonenumber)
       )
FROM tab
GROUP BY name;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This did the trick. I achieved it with (SELECT row_to_json(_) FROM (SELECT name, json_agg(PhoneNumbers) AS PhoneNumbers) AS _) AS t1, but yours is certainly more elegant

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.