使用 AWS Athena 从字符串列中的 JSON 列表中提取数据时获取空白值

问题描述 投票:0回答:1

我有一个包含以下列和数据类型的表格。

id string
name string
title string
listItems string

purchase_list表:

id 名字 标题 列表项目
123 彼得 采购清单 [{"manufacture_date":"2023-01-01","purchase_price":"20.0"}, {"manufacture_date":"2023-01-02","purchase_price":"30.0"}]

使用的查询:

with raw_data as
(
select 
      id
    , name
    , title
    , json_parse(listItems) as listItems
from purchase_list
)
select 
      id
    , name
    , title
    , json_extract_scalar(listItems,'$.manufacture_date') as manufacture_date
    , json_extract_scalar(listItems,'$.purchase_price') as purchase_price
from raw_data

预期输出:

id 名字 标题 制造_日期 购买价格
123 彼得 采购清单 2023-01-01 20.0
123 彼得 采购清单 2023-01-02 30.0

当我使用 json_extract_scalar 提取数据时,我得到空白值

id 名字 标题 列表项目
123 彼得 采购清单

请告知我如何才能达到预期的输出。

json amazon-athena presto
1个回答
0
投票

json_extract_scalar
适用于标量值,数组不是标量值,并且您的 JSON 路径不考虑 JSON 中的数组。处理此问题的一种方法是将 JSON 转换为 JSON 数组并解除嵌套:

-- sample data
with dataset(listItems) as (
    values (json '[{"manufacture_date":"2023-01-01","purchase_price":"20.0"}, {"manufacture_date":"2023-01-02","purchase_price":"30.0"}]')
)

-- query
select json_extract_scalar(item,'$.manufacture_date') as manufacture_date
    , json_extract_scalar(item,'$.purchase_price') as purchase_price
from dataset,
unnest(cast(listItems as array(json))) as t(item);

输出:

制造_日期 购买价格
2023-01-01 20.0
2023-01-02 30.0
© www.soinside.com 2019 - 2024. All rights reserved.