PostgreSql jsonb字段查看

时间:2019-02-07 05:50:40

标签: postgresql

我在我的表“ process”中名为“ FORM”的列中有这种jsonb数据,我想用命名字段内的某些数据创建视图,我只想要名称和值形式字段命名此jsonb中的数组。

此处为jsonb:

 {
      "column": [
        {
          "row": {
            "id": "ebc7afddad474aee8f82930b6dc328fe",
            "name": "Details",
            "field": [
              {
                "name": {
                  "id": "50a5613e97e04cb5b8d32afa8a9975d1",
                  "label": "name"
                },
                "value": {
                  "stringValue": "yhfghg"
                }
              }
            ]
          }
        },
        {
          "row": {
            "id": "5b7471413cbc44c1a39895020bf2ec58",
            "name": "leave details",
            "field": [
              {
                "name": {
                  "id": "bb127e8284c84692aa217539c4312394",
                  "label": "date"
                },
                "value": {
                  "dateValue": 1549065600
                }
              },
              {
                "name": {
                  "id": "33b2c5d1a968481d9d5e386db487de52",
                  "label": "days",
                  "options": {
                    "allowedValues": [
                      {
                        "item": "1"
                      },
                      {
                        "item": "2"
                      },
                      {
                        "item": "3"
                      },
                      {
                        "item": "4"
                      },
                      {
                        "item": "5"
                      }
                    ]
                  },
                  "defaultValue": {
                    "radioButtonValue": "1"
                  }
                },
                "value": {
                  "radioButtonValue": "3"
                }
              }
            ]
          }
        }
      ]
    }

我想视图数据中的这种jsonb来自名为row的对象内称为field的子数组……

[
  {
    "name": {
      "id": "50a5613e97e04cb5b8d32afa8a9975d1"
    },
    "value": {
      "stringValue": "yhfghg"
    }
  },
  {
    "name": {
      "id": "bb127e8284c84692aa217539c4312394"
    },
    "value": {
      "dateValue": 1549065600
    }
  },
  {
    "name": {
      "id": "33b2c5d1a968481d9d5e386db487de52"
    },
    "value": {
      "radioButtonValue": "3"
    }
  }
]

我该怎么做? 谢谢

1 个答案:

答案 0 :(得分:1)

我两次使用jsonb_array_elements来扩展两个数组,然后使用json_build_object来生成结果结构,并且jsonb_agg将上面生成的几行合并为一个JSONB数组。

我包括了行号是结果,因此以后我可以应用group by,以便jsonb_agg不会意外合并来自多个“处理”行的结果。

with cols  as (select jsonb_array_elements( "FORM" ->'column') as r
                     ,row_number() over () as n from  "process" )
    ,cols2 as (select jsonb_array_elements(r->'row'->'field') as v
                     ,n from cols)
select jsonb_agg(json_build_object('name',v->'id','value',v->'value'))
from cols2 group by n;