簡體   English   中英

從sql表中的json中提取所有值

[英]Extract all values from json in sql table

我有一個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

但是,如何提取所有商品(蘋果,橙子)的價格? 作為一個數組。

使用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_keyshttps : json_object_keys

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM