1

I have two tables: product category and products

product category
+----+-------------+
| id | catagory    |
+----+-------------+
| 0  | electronics |
+----+-------------+
| 1  | toys        |
+----+-------------+

products
+----+-----------+-------+--------+
| id | name      | price | ref_id |
+----+-----------+-------+--------+
| 0  | headphone | 100   | 0      |
+----+-----------+-------+--------+
| 1  | phone     | 200   | 0      |
+----+-----------+-------+--------+

How to use row_to_json() to generate the following JSON string:

{
    "catagory": "electronics",
    "products": [
        {
            "name":"headphone",
            "price":100
        },
        {
            "name":"phone",
            "price":200
        }
    ]
}

1 Answer 1

1

You cannot to build this nested expected nested json document by row_to_json function. But it is not too hard:

select json_build_object('category', c.category, 
                         'products', json_agg(json_build_object('name', name, 
                                                                'price', price))) 
 from products 
      join product_category c 
      on ref_id = c.id 
group by c.category;
┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                                   json_build_object                                                   │
╞═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╡
│ {"category" : "electronics", "products" : [{"name" : "headphone", "price" : 100}, {"name" : "phone", "price" : 200}]} │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
(1 row)
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.