避免 JSON 中由 table 行构建的匿名字段

Avoid anonymous fields in JSON built from table rows

我有一个 table:

CREATE TABLE test (
  item_id INTEGER NOT NULL,
  item_name VARCHAR(255) NOT NULL,
  mal_item_name VARCHAR(255),
  active CHAR(1) NOT NULL,
  data_needed CHAR(1) NOT NULL,
  parent_id INTEGER);

查询:

select array_to_json(array_agg(row_to_json(t))) 
from (select item_id as id, 
             item_name as text, 
             parent_id as parent,
             (mal_item_name,data_needed) as data 
      from test) t

产生结果:

[{"id":1,"text":"Materials","parent":0, "data": {"f1":null, "f2":"N"}},
 {"id":2,"text":"Bricks","parent":1,"data":{"f1":null,"f2": "N"}},
 {"id":3,"text":"Class(high)","parent":2,"data":{"f1":null,"f2": "Y"}},
 {"id":4,"text":"Class(low)","parent":2,"data":{"f1":null,"f2": "Y"}}]

原来的字段名mal_item_namedata_needed被替换为f1f2
如何获得带有字段名称本身的 JSON?文档说通过为这两个字段创建一个类型。有其他选择吗?

在 Postgres 9.4 或更高版本中使用 json_build_object()

SELECT json_agg(t) AS js
FROM  (SELECT item_id   AS id
            , item_name AS text
            , parent_id AS parent
            , json_build_object('mal_item_name', mal_item_name
                               ,'data_needed', data_needed) AS data
       FROM test) t;

并使用 json_agg(...) 而不是 array_to_json(array_agg(row_to_json(...)))

对于 Postgres 9.3:

SELECT json_agg(t) AS js
FROM  (SELECT item_id   AS id
            , item_name AS text
            , parent_id AS parent
            , (SELECT t FROM (SELECT mal_item_name, data_needed) 
                                AS t(mal_item_name, data_needed)) AS data
       FROM test) t;

详情: