0

This is a follow-up question of Extract all values from json in sql table

What if the json value has multiple levels?

For example,

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

In this case, I want to extract the price for all the items. But I get error when I run the below query.

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))

I get the below error.

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

If I remove one json_each(), it throws

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

1 Answer 1

1

You can use lateral join, something like:

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
Sign up to request clarification or add additional context in comments.

1 Comment

Wow! You're awesome! Thanks for the info :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.