【问题标题】:Convert standard JSON file to json-serde format using Python & upload to AWS S3 bucket for Amazon Athena (Presto, Hive)使用 Python 将标准 JSON 文件转换为 json-serde 格式并上传到 Amazon Athena(Presto、Hive)的 AWS S3 存储桶
【发布时间】:2020-08-05 22:03:46
【问题描述】:

我正在尝试将 json 文件转换为 json-serde 格式,使用 Python 将 json-serde 文件上传到 AWS S3 存储桶,以便 Amazon Athena (Presto/Hive) 可以读取 s3 存储桶中的文件。

根据 AWS 产品文档,典型的 json 文件不是有效格式; json文件需要是json-serde格式:https://docs.aws.amazon.com/athena/latest/ug/json-serde.html

在本地,我可以使用以下代码将 json 文件转换为 json-serde 格式:

import json
with open('xx_original_file.json','r',encoding='utf-8') as json_file:
    data = json.load(json_file)
result = [json.dumps(record) for record in data]
with open('xx_new_file.json', 'w') as obj:
    for i in result:
        obj.write(i+'\n')

在 Python 中是否有等效的方法可以让我将新的 json-serde 文件存储在 s3 存储桶中?到目前为止,我构建的 Python 脚本一直出错:

import json
import os
import boto3

s3 = boto3.client('s3')
bucket = 'my_bucket_name'
key = 'xx_original_file.json'
response = s3.get_object(Bucket=bucket,Key=key)
content = response['Body']
jsonObject = json.loads(content.read())
result = [json.dumps(record) for record in jsonObject]
new_results = []
for i in result:
    new_results.append(i+'\n')
new_key = 'xx_new_file.json'
s3.put_object(Bucket=bucket,Key=new_key,Body=new_results)

错误信息:ParamValidationError:参数验证失败: 参数 Body 的类型无效,值:{json data} 类型:,有效类型:,,类文件对象

【问题讨论】:

  • 您可以打印 new_results() 并查看您传递给 Body 的具体内容吗?

标签: python json amazon-s3 hive amazon-athena


【解决方案1】:

这是一个简单的解决方法,我需要将列表转换为字符串,然后将其转换为字节。

import json
import boto3
s3 = boto3.client('s3')
bucket = 'my_bucket_name'
key = 'xx_original_file.json'
response = s3.get_object(Bucket=bucket,Key=key)
content = response['Body']
jsonObject = json.loads(content.read())
result = "\n".join([json.dumps(record) for record in jsonObject])
body = result.encode('utf-8')
new_bucket = 'my_bucket_name'
new_key = 'xx_new_file.json'
s3.put_object(Bucket=new_bucket,Key=new_key,Body=body)

【讨论】:

    猜你喜欢
    • 2021-11-03
    • 2019-09-05
    • 1970-01-01
    • 1970-01-01
    • 2019-04-28
    • 2018-04-25
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多