首页 > 解决方案 > 将 AWS 胶水输出格式化为 JSON OBJECT

问题描述

这是我在 AWS GLUE 中的 pyspark 工作得到的结果

{a:1,b:7}
{a:1,b:9}
{a:1,b:3}

但我需要在 s3 上写入这些数据并以 JSON 数组格式将其发送到 API

[
 {a:1,b:2}, 
 {a:1,b:7}, 
 {a:1,b:9}, 
 {a:1,b:3}
]

我尝试将我的输出转换为 DataFrame 然后应用 toJSON() results = mapped_dyF.toDF() jsonResults = results.toJSON().collect()

但现在无法在 s3 上写回结果,'write_dynamic_frame.from_options' 因为它需要 DF,但我'jsonResults'现在不再是 DataFrame。

标签: pysparkaws-glue

解决方案


为了将其放入 JSON 数组格式,我通常执行以下操作:df --> 包含原始数据的 DataFrame。

if df.count() > 0:
    # Build the json file
    data = list()
    for row in df.collect():
        data.append({"a": row['a'],
                     "b" : row['b']
                    })

在这种情况下,我没有使用 Glue write_dynamic_frame.from_options,但我使用它boto3来保存文件:

import boto3
import json

s3 = boto3.resource('s3')
# Dump the json file to s3 bucket  
filename = '/{0}_batch_{1}.json'.format(str(uuid.uuid4()))
obj = s3.Object(bucket_name, filename)
obj.put(Body=json.dumps(data))

推荐阅读