【发布时间】:2019-05-06 16:05:57
【问题描述】:
假设我们在 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" }
【问题讨论】:
标签: arrays json postgresql