给定一个对象数组,我们可以使用jsonb_to_recordset将其转换为记录集。
select * from jsonb_to_recordset($$[
{"name": "name01", "age": 12},
{"name": "name02", "age": 14},
{"name": "name03", "age": 16},
{"name": "name04", "age": 18}
]$$) as (name text, age int)
name |age |
-------|----|
name01 |12 |
name02 |14 |
name03 |16 |
name04 |18 |
但是如果我们更喜欢数组数组形式的源数据呢?如何转换下面的查询以产生类似的结果?
select array['name', 'age'] "labels"
, x.value "values"
from jsonb_array_elements($$[
["name01", 12],
["name02", 14],
["name03", 16],
["name04", 18]
]$$) x
labels |values |
-----------|---------------|
{name,age} |["name01", 12] |
{name,age} |["name02", 14] |
{name,age} |["name03", 16] |
{name,age} |["name04", 18] |
答案 0 :(得分:2)
您可以使用->>
:
select x.value->>0 AS name,
x.value->>1 AS age
from jsonb_array_elements($$[
["name01", 12],
["name02", 14],
["name03", 16],
["name04", 18]
]$$) x;
输出:
+--------+-----+
| name | age |
+--------+-----+
| name01 | 12 |
| name02 | 14 |
| name03 | 16 |
| name04 | 18 |
+--------+-----+
<强> DBFiddle Demo 强>