简体   繁体   中英

How do I extract all of the values from a JSON element?

How can I extract all of the values for the element account_code ? The below SELECT statement lets me extract any single value associated with index [x] but I want to extract all the values (each in it's own row) such that the output is:

account_codes
------------
1
2
3

SELECT
    JSON_EXTRACT_SCALAR(v, '$.accounting[0].account_code') AS account_codes
FROM (VALUES JSON '
    {"accounting":
        [
            {"account_code": "1", "account_name": "Travel"},
            {"account_code": "2", "account_name": "Salary"},
            {"account_code": "3", "account_name": "Equipment"},
        ]
    }'
) AS t(v)

The operator you need to use is unnest which will flatten the array and fetch you all the column values. Below is the query and DDL in hive catalog I used to create table and fetch all account codes

DDL:

CREATE EXTERNAL TABLE `sf_73515497`(
  `accounting` array<struct<account_code:string,account_name:string>> COMMENT 'from deserializer')
ROW FORMAT SERDE 
  'org.openx.data.jsonserde.JsonSerDe' 
WITH SERDEPROPERTIES ( 
  'paths'='accounting') 
STORED AS INPUTFORMAT 
  'org.apache.hadoop.mapred.TextInputFormat' 
OUTPUTFORMAT 
  'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
  's3://path-to-json-prefix/'

SQL with unnest:

WITH dataset AS (
  SELECT accounting from "sf_73515497" 
)
SELECT t.accounts.account_code FROM dataset
CROSS JOIN UNNEST(accounting) as t(accounts)

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