[英]How do I select all from a nested array of JSON objects?
我有一个 PostgreSQL 表,每一行都包含 JSON 对象,看起来像这样:
{
"Metadata":{
...
},
"NestedArray":[
{
...,
...,
"Coordinates":[
{
"id":"1000",
"X":"...",
"Y":"..."
},
{
"id":"1001",
"X":"...",
"Y":"..."
},
{
"id":"1003",
"X":"...",
"Y":"..."
}
]
}
]
}
所以每个对象都包含一个NestedArray
,它包含另一个名为Coordinates
嵌套数组。
MyObject.NestedArray[].Coordinates[]
我想要做的是在我的 PostgreSQL 表中查询一个 JSON 列,该列包含诸如上述对象的对象,并获得所有Coordinates
对象的结果集。
所以这基本上就是我想要的结果:
ID | X | 是 |
---|---|---|
1001 | . | . |
1002 | . | . |
1003 | . | . |
1004 | . | . |
1005 | . | . |
1006 | . | . |
我该怎么做?
我认为 jsonb_array_elements() 在这种情况下不起作用,因为有两个嵌套级别的 json 数组。 这应该进行测试:
SELECT r.item ->> 'id' as id
, r.item ->> 'X' as X
, r.item ->> 'Y' as Y
FROM your_table
CROSS JOIN LATERAL jsonb_path_query(your_json_column :: jsonb, '$.NestedArray[*].Coordinates[*]') AS r(item)
您需要取消嵌套数组,然后您可以使用->>
运算符访问每个键:
select e.item ->> 'id' as id,
e.item ->> 'x' as x,
e.item ->> 'y' as y
from the_table
cross join jsonb_array_elements(the_column -> 'NestedArray' -> 'Coordinates') as x(item)
这假设the_column
是用数据类型jsonb
(应该是)定义的。 如果不是使用json_array_elements()
代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.