This question already has answers here:
PostgreSQL 9.2 row_to_json() with nested joins
(2个答案)
四年前关闭。
我有一张桌子:
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”:空,“f2”:“N”},
{“id”:2,“text”:“Bricks”,“parent”:1,“data”:{“f1”:空,“f2”:“N”},
{“id”:3,“text”:“Class(high)”,“parent”:2,“data”:{“f1”:空,“f2”:“Y”},
{“id”:4,“text”:“Class(low)”,“parent”:2,“data”:{“f1”:空,“f2”:“Y”}]
原始字段名mal_item_namedata_needed替换为f1f2
如何获取具有字段名本身的JSON?文档说明为这两个字段创建一个类型。有别的选择吗?

最佳答案

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

细节:
Return as array of JSON objects in SQL (Postgres)
PostgreSQL 9.2 row_to_json() with nested joins
PostgreSQL : select columns inside json_agg

关于json - 避免从表行构建的JSON中的匿名字段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28066171/

10-13 01:55