[英]Postgresql get elements of a JSON array
假设我们在Postgresql中具有以下JSON:
{ "name": "John", "items": [ { "item_name": "lettuce", "price": 2.65, "units": "no" }, { "item_name": "ketchup", "price": 1.51, "units": "litres" } ] }
JSON存储在下表中:
create table testy_response_p (
ID serial NOT NULL PRIMARY KEY,
content_json json NOT NULL
)
insert into testy_response_p (content_json) values (
'{ "name": "John", "items": [ { "item_name": "lettuce", "price": 2.65, "units": "no" }, { "item_name": "ketchup", "price": 1.51, "units": "litres" } ] }'
)
由于以下内容可以返回JSON或文本(分别使用->
和->>
select content_json ->> 'items' from testy_response_p
),因此我想使用子查询来获取items
下数组的元素:
select *
from json_array_elements(
select content_json ->> 'items' from testy_response_p
)
我得到的只是一个错误,但我不知道自己在做什么错。 子查询的输出是文本。 最终输出为:
{ "item_name": "lettuce", "price": 2.65, "units": "no" }
{ "item_name": "ketchup", "price": 1.51, "units": "litres" }
您需要加入函数的结果。 您不能使用->>
运算符,因为它会返回文本,而json和json_array_elements()
只能使用JSON值作为其输入。
select p.id, e.*
from testy_response_p p
cross join lateral json_array_elements(p.content_json -> 'items') as e;
在线示例: https : //rextester.com/MFGEA29396
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.