简体   繁体   中英

SQL: JSON Extract from nested object

I have a table like this

id obj
1 {"is_from_shopping_bag":true,"products":[{"price":{"amount":"18.00","currency":"USD","offset":100,"amount_with_offset":"1800"},"product_id":"1234","quantity":1}],"source":"cart"}
2 {"is_from_shopping_bag":false,"products":[{"price":{"amount":"80.00","currency":"USD","offset":100,"amount_with_offset":"8000"},"product_id":"2345","quantity":1}],"source":"pdp"}

I am doing a sql query in Hive to get the 'currency' field.

Currently I can run

SELECT
    JSON_EXTRACT( obj, '$.products')
FROM my_table

Which returns

obj
[{"price":{"amount":"18.00","currency":"USD","offset":100,"amount_with_offset":"1800"},"product_id":"1234","quantity":1}]
[{"price":{"amount":"80.00","currency":"USD","offset":100,"amount_with_offset":"8000"},"product_id":"2345","quantity":1}]

How do I go a layer deeper to get the currency?

To get the currency of the first product use:

SELECT
    id,JSON_EXTRACT( obj, '$.products[0].price.currency') first_product_currency
FROM my_table;
id first_product_currency
1 "USD"
2 "USD"

To get the currency of all the products use:

SELECT
    id,JSON_EXTRACT( obj, '$.products[*].price.currency') multiple_currencies
FROM my_table;
id multiple_currencies
1 ["USD"]
2 ["USD"]

View on DB Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM