如何显示存储在jsonb中的数组

时间:2017-07-13 12:05:04

标签: postgresql

我在postgres(9.5)数据库的jsonb列中存储了数据信息:

    {
        "status" : "NOK",
        "info" : [{
            "type" : "TYPE1",
            "error" : [],
            "values" : [-44.995882968879044, -32.84752217736367, -18.645252496214137, -5.917307355383778],
            "sources" : [{
                        "id" : "54374c62",
                        "type" : "regular",
                            "distance" : {
                                "to" : 0.9378531073446326,
                                "from" : 0.0
                            }
                        }
                    ],
                    "algorithm" : "rel",
                }
            ]
         }

我想在“info as new columns”中显示“values”和“algorithm”。这是我的示例查询。有什么帮助吗?

SELECT id,
 column_jsonb -> 'status' as status,
 column_jsonb -> 'info' -> 'value' as value,
 column_jsonb -> 'info' -> 'type' as type,
 column_jsonb -> 'info' -> 'algorithm' as algorithm

  FROM data.transaction
where id = '8db348e1-a8ec'

1 个答案:

答案 0 :(得分:1)

您可以使用jsonb_array_elements

with the_table(id, column_jsonb ) as(
select  '8db348e1-a8ec'::text, '{"status" : "NOK",
    "info" : [{
    "type" : "TYPE1",
    "error" : [],
    "values" : [-44.995882968879044, -32.84752217736367, -18.645252496214137, -5.917307355383778],
    "sources" : [{
        "id" : "54374c62",
        "type" : "regular",
        "distance" : {
        "to" : 0.9378531073446326,
        "from" : 0.0
        }
        }
        ],
        "algorithm" : "rel"
    }
    ]
     }'::jsonb 
)

select 
the_table.id,
the_table.column_jsonb->'status',
j.value->'type',
j.value->'values',
j.value->'algorithm'
from the_table
join lateral jsonb_array_elements(column_jsonb -> 'info') as j
on true

where
the_table.id = '8db348e1-a8ec'

请注意,如果info数组中有多个元素,则会得到相同行的重复结果。