首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >json在sql中提取多级值。

json在sql中提取多级值。
EN

Stack Overflow用户
提问于 2017-07-11 06:59:00
回答 1查看 369关注 0票数 0

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

如果json值有多个级别怎么办?

例如,

代码语言:javascript
复制
{
    "store-1": {
        "Apple": {
            "category": "fruit",
            "price": 100
        },
        "Orange": {
            "category": "fruit",
            "price": 80
        }
    },
    "store-2": {
        "Orange": {
            "category": "fruit",
            "price": 90
        },
        "Potato": {
            "category": "vegetable",
            "price": 40
        }
    }
}

在这种情况下,我想提取所有项目的价格。但是,当我运行下面的查询时会出现错误。

代码语言:javascript
复制
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))

我得到了以下错误。

代码语言:javascript
复制
ERROR:  function json_each(record) does not exist
LINE 10: json_each(json_each(items))

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

代码语言:javascript
复制
ERROR:  operator does not exist: json -> json
LINE 8: select key, (value->value->>'price')::numeric as price
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-11 07:23:32

您可以使用横向连接,类似于:

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45027506

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档