sql - json在sql中提取多级值

标签 sql json postgresql

这是Extract all values from json in sql table的后续问题

如果json值有多个层次怎么办?

例如,

{
    "store-1": {
        "Apple": {
            "category": "fruit",
            "price": 100
        },
        "Orange": {
            "category": "fruit",
            "price": 80
        }
    },
    "store-2": {
        "Orange": {
            "category": "fruit",
            "price": 90
        },
        "Potato": {
            "category": "vegetable",
            "price": 40
        }
    }
}

在本例中,我想提取所有商品的价格。但是当我运行以下查询时出现错误。

with my_table(items) as (
    values (
    '{"store-1":{"Apple":{"category":"fruit","price":100},"Orange":{"category":"fruit","price":80}},
    "store-2":{"Orange":{"category":"fruit","price":90},"Potato":{"category":"vegetable","price":40}}}'::json
    )
)

select key, (value->value->>'price')::numeric as price
from my_table,
json_each(json_each(items))

我收到以下错误。

ERROR:  function json_each(record) does not exist
LINE 10: json_each(json_each(items))

如果我删除一个 json_each(),它会抛出

ERROR:  operator does not exist: json -> json
LINE 8: select key, (value->value->>'price')::numeric as price

最佳答案

您可以使用横向连接,例如:

with my_table(items) as (
    values (
    '{"store-1":{"Apple":{"category":"fruit","price":100},"Orange":{"category":"fruit","price":80}},
    "store-2":{"Orange":{"category":"fruit","price":90},"Potato":{"category":"vegetable","price":40}}}'::json
    )
)

select outer_key, key, value->>'price' from (
    select key as outer_key, value as val from my_table 
    join lateral json_each(items) 
    on true
)t
join lateral json_each(val) 
on true

关于sql - json在sql中提取多级值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45027506/

相关文章:

java - 如何在sql中转义 "'”

sql - 选择查询中的依赖列

php - 如何将 Guzzle Mock Handler 传递给 PHP 类以测试具有 json 响应的 API 调用

javascript - JSON.解析得到 "Uncaught SyntaxError: Unexpected token h"

ruby-on-rails - Rails 未运行迁移

mysql - Doctrine2 链式多表连接和过滤

php - 如何将值插入联结表?

c++ - 反对 Json 并返回

postgresql - PostgreSQL中如何设置sub select的表空间

sql - 如何在for循环中执行多个查询