避免在表行中构建JSON中的匿名字段

时间:2015-01-21 11:31:39

标签: json postgresql field anonymous

我有一张桌子:

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?文档说通过为这两个字段创建一个类型。还有其他选择吗?

1 个答案:

答案 0 :(得分:0)

在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;

详细说明: