如何使用PostgreSQL从多个表中返回单个JSON对象

时间:2016-11-12 18:54:57

标签: json postgresql

使用以下代码片段,我正在构建一个有效的JSON字符串:

(SELECT CONCAT('{', array_to_string(array_agg(info),','), '}')
 FROM (
          SELECT CONCAT('"', "displayOrder", '":', 
                        CONCAT('{"milestoneID":', 
                               "milestoneID"::TEXT, 
                               ',"msValue":"',  
                               "msValue", 
                               '","msColor":"', 
                               "msColor", '"}'
                               )
                        ) AS info
          FROM "fileMilestones"
              LEFT JOIN milestones ON "fileMilestones"."milestoneID" = milestones.id
          WHERE "fileMilestones"."fileNumber" = wc_files."fileNumber"
      ) AS msa
) AS ms,

但是,它只是一个字符串,不会被视为JSON对象。我确信我做错了......

这是表结构:

CREATE TABLE public."fileMilestones"
(
  id integer NOT NULL DEFAULT nextval('"fileMilestones_id_seq"'::regclass),
  "fileNumber" integer,
  "milestoneID" smallint,
  "msValue" text,
  "msColor" text,
  CONSTRAINT "fileMilestones-id.constraint" PRIMARY KEY (id),
  CONSTRAINT "fileMilestones-fileNumber-milestoneID.constraint" UNIQUE ("fileNumber", "milestoneID")
)

CREATE TABLE public.milestones
(
  id integer NOT NULL DEFAULT nextval('milestones_id_seq'::regclass),
  "displayOrder" smallint,
  name citext,
  days smallint,
  start smallint,
  "calendarDays" smallint,
  description citext,
  "moduleID" integer,
  CONSTRAINT "milestones-id.constraint" PRIMARY KEY (id),
  CONSTRAINT "milestones-name.constraint" UNIQUE (name)
)

这是返回的JSON需要的样子:

{"10":{"milestoneID":1, "msValue":"", "msColor":"milestoneColorGreen"}, 
 "20":{"milestoneID":2, "msValue":"", "msColor":"milestoneColorGreen"},
 "30":{"milestoneID":3, "msValue":"", "msColor":"milestoneColorGreen"},
 "40":{"milestoneID":4, "msValue":"", "msColor":"milestoneColorGreen"},
 "50":{"milestoneID":10, "msValue":"", "msColor":"milestoneColorGreen"},
 "60":{"milestoneID":6, "msValue":"", "msColor":"milestoneColorGreen"},
 "70":{"milestoneID":7, "msValue":"", "msColor":"milestoneColorGreen"},
 "80":{"milestoneID":8, "msValue":"76", "msColor":""},
 "90":{"milestoneID":9, "msValue":"", "msColor":"milestoneColorGreen"}}

如何构建JSON对象并将其作为JSON返回?

1 个答案:

答案 0 :(得分:2)

最简单的解决方案是使用::json将最终结果转换为JSON,但确实希望使用内置的JSON支持来完成这些事情。在最简单的JSON结构之上的任何东西很快就会变得非常繁琐,无法在代码中指定,容易出错并且难以维护。

但是要回答你的问题(在帖子的底部),你可以用...... json_build_object()“构建一个JSON对象”。您可以使用json_object_agg()函数聚合键/值对。这两个函数都有一个jsonb变体。

SELECT json_object_agg("displayOrder"::text, 
                       json_build_object('milestoneID', "milestoneID"::text, 
                                         'msValue', "msValue", 
                                         'msColor', "msColor")) AS info
FROM "fileMilestones"
LEFT JOIN milestones ON "fileMilestones"."milestoneID" = milestones.id
WHERE "fileMilestones"."fileNumber" = wc_files."fileNumber" -- wc_files???
...