首页 > 解决方案 > 如何关系化包含数组的 JSON

问题描述

我正在使用 AWS Glue 读取包含 JSON 的数据文件(在 S3 上)。这是一个 JSON,其数据包含在数组中。我曾尝试使用关系化()函数,但它不适用于数组。它确实适用于嵌套的 JSON,但这不是输入的数据格式。

有没有办法将 JSON 与其中的数组关联起来?

输入数据:

{
    "ID":"1234",
    "territory":"US",
    "imgList":[
        {
            "type":"box"
            "locale":"en-US"
            "url":"boxart/url.jpg"
        },
        {
            "type":"square"
            "locale":"en-US"
            "url":"square/url.jpg"
        }
    ]
}

代码:

dfc = Relationalize.apply(frame = datasource0, staging_path = glue_temp_storage, name = "root", transformation_ctx = "dfc")
dfc.select('root').toDF().show()

输出:

+----+----------+--------+
|ID  |territory |imgList |
+----+----------+--------+
|1234|       US |       1|
+----+----------+--------+

期望的输出:

+----+----------+-------------+---------------+---------------+
|ID  |territory |imgList.type |imgList.locale |imgList.url    |
+----+----------+-------------+---------------+---------------+
|1234|       US |       box   |         en-US |boxart/url.jpg |
+----+----------+-------------+---------------+---------------+
|1234|       US |       square|         en-US |square/url.jpg |
+----+----------+-------------+---------------+---------------+

标签: amazon-web-servicesamazon-s3pysparkaws-glue

解决方案


Relationalize 为 JSON 文档中的每个数组创建 DynamicFrames。所以你只需要得到它并加入根表:

dfc = Relationalize.apply(frame = datasource0, staging_path = glue_temp_storage, name = "root", transformation_ctx = "dfc")
root_df = dfc.select('root')
imgList_df = dfc.select('root_imgList')

df = Join.apply(root_df, imgList_df, 'imgList', 'id')
df.toDF().show()

推荐阅读