我有一个表格形式的数据库表
CREATE TABLE products(
id SERIAL PRIMARY KEY,
category TEXT,
name TEXT,
price REAL,
weight REAL);
,我想以
格式为我的API输出JSON。[{"category":"category name",
"products":[{"name":"product name one","price":4.44,"weight":0.5},
{"name":"product name two","price":6.45,"weight":1.0}]}]
因此,如果我的表中包含以下条目:
INSERT INTO products (category, name, price, weight)
VALUES ("toothpaste","Chrest Pro-White",4.99,6.4),
("toothpaste","Colgate Cavity Prevention",3.99,6.4),
("body wash","Old Spice Hydro",5.99,16.0),
("body wash","Axe Apollo",8.99,22.0);
API应该返回
[{"category":"toothpaste",
"products":[{"name":"Chrest Pro-White","price":4.99,"weight":6.4},
{"name":"Colgate Cavity Prevention","price":3.99,"weight":6.4}]},
{"category":"body wash",
"products":[{"name":"Old Spice Hydro","price":5.99,"weight":16.0},
{"name":"Axe Apollo","price":8.99,"weight":22.0}]}]
我可以遍历表中的所有行,并为每个唯一的类别名称手动创建json对象,但是我希望有一种更好的方法。
答案 0 :(得分:1)
有很多方法可以通过使用ORM并从API服务器创建json来实现,但是您也可以直接在postgres中实现:
select json_agg(categories)
FROM (
SELECT json_build_object(
'category', category,
'products', json_agg(
json_build_object(
'name', name,
'price', price,
'weight', weight)
)
) as categories
FROM products
GROUP BY category) sub;
[{"category" : "toothpaste", "products" : [{"name" : "Chrest Pro-White", "price" : 4.99, "weight" : 6.4}, {"name" : "Colgate Cavity Prevention", "price" : 3.99, "weight" : 6.4}]}, {"category" : "body wash", "products" : [{"name" : "Old Spi
ce Hydro", "price" : 5.99, "weight" : 16}, {"name" : "Axe Apollo", "price" : 8.99, "weight" : 22}]}]
答案 1 :(得分:0)
您可以使用此 console.log(JSON.stringify(data));