1

I'm trying to write a query on my food.list table:

categories    | items
----------------------------
dairy         | ["milk", "cheese"]
fruit         | ["apples", "pears", "grapes"]
vegetables    | ["carrots"]  

and return a selected_foods column with a single row. I want the row's value to be an object with a list of categories (keys) with an array of items (values).

selected_foods
------------------------------------
{ 
  dairy: ["milk", "cheese"], 
  fruit: ["apples", "pears", "grapes"], 
  vegetables: ["carrots"] 
}

So far, I've tried:

SELECT json_agg(json_build_object(categories, items::json))::json 
AS selected_foods
FROM food.list

But this returns an array of objects, i.e.:

selected_foods
------------------------------------
[ 
  { dairy: ["milk", "cheese"] }, 
  { fruit: ["apples", "pears", "grapes"] }, 
  { vegetables: ["carrots"] }
]

I think I'm applying the json_build_object function too early...or maybe I need to unwrap them again after?

Any help would be awesome, thanks :)

1 Answer 1

2

Use json_object_agg

SELECT json_object_agg( categories, items::json)  as selected_foods
     from list 

DEMO

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.