[英]Extract all values from json in sql table
I have a postgresql table which has a column in json format. 我有一个postgresql表,其中有json格式的列。
Sample column value: 样本列值:
{"Apple":{"category":"fruit","price":100},"Orange":{"category":"fruit","price":80}}
Now I want to select this column, and extract the "price"
for all items in each row. 现在,我要选择此列,并提取每一行中所有项目的
"price"
。
Query to get column: 查询以获取列:
select items from my_table
To extract the json value for a specific item, I can use 要提取特定项目的json值,我可以使用
select items -> 'Orange' -> 'price' as price
from my_table
But how do I extract the price for all the items (Apple, Orange)? 但是,如何提取所有商品(苹果,橙子)的价格? As an array maybe.
作为一个数组。
Use json_each()
, eg: 使用
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)
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 json_object_keys
: https : json_object_keys
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.