在Postgres中获取数组数据Json

时间:2019-10-11 10:18:29

标签: json postgresql

我在表中运行的Json字段中填充了来自流程的数据,就像这样

{
"output": {
    "DATA": [
        [
            {
                "NumOrdem": "136726",
                "NumCliente": "4594731",
                "numConta": "440.10.600324-5",
                "numNota": "",
                "numCativo": "000001",
                "mensagem": "Mainframe - CL57 - Numero de referencia nao existe nas notas."
            }
        ],
        [
            {
                "NumOrdem": "136726",
                "NumCliente": "4594731",
                "numConta": "440.10.600324-5",
                "numNota": "",
                "numCativo": "000003",
                "mensagem": "Mainframe - CL57 - Numero de referencia nao coincide."
            }
        ]
    ]
}

}

并希望通过Postgres提取此数据,以得到如下所示的信息:

enter image description here

这可行吗?

1 个答案:

答案 0 :(得分:0)

您需要取消嵌套数组:

select data.jv ->> 'NumOrdem' as "NumOrdem",
       data.jv ->> 'NumCliente' as "NumCliente",
       data.jv ->> 'numConta' as "numConta", 
       data.jv ->> 'numNota' as "numNota",
       data.jv ->> 'numCativo' as "numCativo",
       data.jv ->> 'mensagem' as "mensagem"
from the_table t
  cross join jsonb_array_elements(t.output -> 'output' -> 'DATA') as a1(j1)
  cross join jsonb_array_elements(a1.j1) as data(jv)

jsonb_array_elements将数组的每个元素作为JSON值返回,外部查询只是从该JSON值中选择键。

as data(jv)定义了table alias和列名

如果您使用的不是jsonb(为什么?),而是json,那么您需要使用json_array_elements()

在线示例:https://rextester.com/XVYA32320