【问题标题】:Postgresql get elements of a JSON arrayPostgresql 获取 JSON 数组的元素
【发布时间】: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


    【解决方案1】:

    您需要加入函数的结果。您不能使用 ->> 运算符,因为它返回文本,而不是 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

    【讨论】:

      猜你喜欢
      • 2016-08-20
      • 1970-01-01
      • 2012-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多