简体   繁体   English

Postgres SQL 查询,返回带有来自一列的键和来自另一列的值的 JSON 对象

[英]Postgres SQL Query that returns JSON object with keys from one column and values from another column

I want to create a (Postgres) SQL Query that returns a JSON object.我想创建一个返回 JSON 对象的(Postgres)SQL 查询。 The keys should be the entries from one column (eg. ID) and the values the entries from another column (eg. name).键应该是来自一列的条目(例如 ID)和来自另一列的条目(例如名称)的值。 My table looks like this:我的桌子看起来像这样:

CREATE TABLE foods (
  id SERIAL PRIMARY KEY, 
  name VARCHAR(100)
);
INSERT INTO foods(name)
VALUES  ('Apple'),
        ('Banana'),
        ('Lemon');

Running example: https://dbfiddle.uk/?rdbms=postgres_12&fiddle=96c8ee3de02647333752a30b9cfc8674运行示例: https : //dbfiddle.uk/?rdbms=postgres_12&fiddle=96c8ee3de02647333752a30b9cfc8674

The result should look like this:结果应如下所示:

{
  "1": "Apple",
  "2": "Banana",
  "3": "Lemon"
}

Just use json[b]_object_agg() :只需使用json[b]_object_agg()

select jsonb_object_agg(id, name) res
from foods 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM