我有一个postgresql表,它有一个json格式的列。
示例列值:
{"Apple":{"category":"fruit","price":100},"Orange":{"category":"fruit","price":80}}
现在我想选择此列,并为每行中的所有项目提取"price"
。
查询获取列:
select items from my_table
要提取特定项目的json值,我可以使用
select items -> 'Orange' -> 'price' as price
from my_table
但是如何提取所有商品(Apple,Orange)的价格?作为阵列可能。
答案 0 :(得分:1)
使用json_each()
,例如:
with my_table(items) as (
values (
'{"Apple":{"category":"fruit","price":100},"Orange":{"category":"fruit","price":80}}'::json
)
)
select key, (value->>'price')::numeric as price
from my_table,
json_each(items)
key | price
--------+-------
Apple | 100
Orange | 80
(2 rows)
答案 1 :(得分:1)
t=# with my_table(items) as (
values('{"Apple":{"category":"fruit","price":100},"Orange":{"category":"fruit","price":80}}'::json)
)
select
json_object_keys(items)
, items->json_object_keys(items)->>'price'
from my_table;
json_object_keys | ?column?
------------------+----------
Apple | 100
Orange | 80
(2 rows)
json_object_keys
:
https://www.postgresql.org/docs/9.5/static/functions-json.html