json的postgres columns属性

时间:2013-09-10 16:38:47

标签: json postgresql nginx

我目前是ngx_postgres的快乐用户。但是我最近发现我需要做一些非常奇怪的事情。基本上我需要生成以下json输出:

{
     "PatientName": {
         "Tag": "00100010",
         "VR": "PN",
         "PersonName": [
           {
             "SingleByte": "Wang^XiaoDong",
             "Ideographic": "王^小東"
           }
         ]
     },
},
{
     "PatientName": {
         "Tag": "00100010",
         "VR": "PN",
         "PersonName": [
           {
             "SingleByte": "John^Doe",
           }
         ]
     },
}

通过对DICOM标准的一点阅读,可以轻松创建(简化)关键字,标签和VR的等效表:

CREATE TABLE equiv (
    "Keyword" varchar(64) PRIMARY KEY,
    "Tag" char(8) NOT NULL,
    "VR" char(2) NOT NULL,
);

现在,棘手的部分是与PatientName的间接,我不明白,我试过:

CREATE TABLE patientname (
    "SingleByte" varchar(64) primary key,
    "Ideographic" varchar(64),
);
CREATE TABLE patientlevel_impl_detail (
    "PatientName" varchar(64) references patientname("SingleByte"),
    "PatientID" character varying(64) NOT NULL
);
CREATE view patientlist as select
patientname."SingleByte",
patientname."Ideographic",
patientname."Phonetic",
patientlevel_impl_detail."PatientID"
FROM patientlevel_impl_detail,patientname where patientlevel_impl_detail."PatientName" = patientname."SingleByte";

然而,在任何情况下,TABLE和/或VIEW总是变平,而是我得到类似的东西:

$ curl http://localhost:8080/patients
[
     {
         "Tag": "00100010",
         "VR": "PN",
         "SingleByte": "John^Doe",
         "Ideographic": null,
     },
]

所以我看不出如何将PersonName设为嵌套字符串数组(嵌套json树)。

注意:我没有使用9.3,我现在需要使用9.1

1 个答案:

答案 0 :(得分:1)

在9.1上,帮自己一个忙,获得9.1的json extension。它会为你节省很多工作。

您需要做的第二件事是创建一个嵌套数据结构作为与您的json结构匹配的视图。您将使用array_agg():

CREATE view patientlist as select
arrayagg(patientname) as "PatientName"
patientlevel_impl_detail."PatientID"
FROM patientlevel_impl_detail,patientname 
where patientlevel_impl_detail."PatientName" = patientname."SingleByte";

然后你应该能够:

SELECT row_to_json(patientlist) FROM patientlist;