Select 作为 JSON 对象 {key: {}}

Select as JSON object {key: {}}

我的table:

ID | something1 | something2 | ...
1  | meow       | 5          |
2  | 4          | KITTIES    |

有什么方法可以将 select 数据设为 JSON 格式 {"1":{"something1":"meow","something2":5},"2":{...}} 吗?

您可以使用 this library 获取数据库的 API。然后,消耗它!这是我能想到的最快最清楚的事情了。

如果您不介意在行的 JSON 表示中重复 ID 字段,您可以这样做:

SELECT 
  format('{%s}',
    string_agg(
      format(
        '%s:%s',
        to_json(ID::text),
        row_to_json(my_table)
      ), ','
    ), ''
  )::json as json_object
FROM my_table;

这为您提供了一个 JSON 对象,其中包含 table 中每一行的子对象,由 ID 字段中的值作为键值。

SQLFiddle

有关详细信息,请参阅 this question