【问题标题】:Merging multiple JSON files into single JSON file in S3 from AWS Lambda python function从AWS Lambda python函数将多个JSON文件合并到S3中的单个JSON文件
【发布时间】:2022-01-23 20:43:27
【问题描述】:

我对我的工作感到震惊,我的要求是将多个 json 文件组合成单个 json 文件并需要将其压缩到 s3 文件夹中

我以某种方式做到了,但 json 内容正在字典中合并,我知道我已经使用 Dictionary 从文件中加载我的 json 内容,因为我尝试加载为 List 但它抛出 mw JSONDecodeError "Extra data:line 1 column 432(431 )"

我的文件如下所示: file1(不会有 .json 扩展名)

{"abc":"bcd","12354":"31354321"}

文件 2

{"abc":"bcd","12354":"31354321":"hqeddeqf":"5765354"}

我的代码-

import json
import boto3

s3_client=boto3.client('s3')

bucket_name='<my bucket>'

def lambda_handler(event,context):
 key='<Bucket key>'
 jsonfilesname = ['<name of the json files which stored in list>']
 result=[]
 json_data={}
 for f in (range(len(jsonfilesname))):
  s3_client.download_file(bucket_name,key+jsonfilesname[f],'/tmp/'+key+jsonfilesname[f])
  infile = open('/tmp/'+jsonfilesname[f]).read()
  json_data[infile] = result
 with open('/tmp/merged_file','w') as outfile:
  json.dump(json_data,outfile)

上面代码输出的outfile是

{
"{"abc":"bcd","12354":"31354321"}: []",
"{"abc":"bcd","12354":"31354321":"hqeddeqf":"5765354"} :[]"
}

我的期望是:

{"abc":"bcd","12354":"31354321"},{"abc":"bcd","12354":"31354321":"hqeddeqf":"5765354"}

请有人帮助和建议需要做些什么才能达到我的预期输出

【问题讨论】:

  • 在这行代码:json_data[infile] = resultinfile是从JSON文件中读取的文本,result是一个空数组。这就是为什么你会得到你所看到的结果。您可能应该使用json_data.push(infile)。此外,您的预期输出不是有效的 JSON。您的意思是要将两个对象包装在一个数组中吗?

标签: python json amazon-web-services amazon-s3 aws-lambda


【解决方案1】:

首先:

file 2 不是一个有效的 JSON 文件,它应该是:

{
    "abc": "bcd",
    "12354": "31354321",
    "hqeddeqf": "5765354"
}

另外,输出不是一个有效的 JSON 文件,合并 2 个 JSON 文件后你会期望得到一个 JSON 对象数组:

[
    {
        "abc": "bcd",
        "12354": "31354321"
    },
    {
        "abc": "bcd",
        "12354": "31354321",
        "hqeddeqf": "5765354"
    }
]

知道了这一点,我们可以编写一个 Lamdda 来合并 JSONS 文件:

import json
import boto3

s3 = boto3.client('s3')

def lambda_handler(event,context):
    bucket = '...'
    jsonfilesname = ['file1.json', 'file2.json']
    result=[]
    for key in jsonfilesname:
        data = s3.get_object(Bucket=bucket, Key=key)
        content = json.loads(data['Body'].read().decode("utf-8"))
        result.append(content)

    # Do something with the merged content
    print(json.dumps(result))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 2017-10-26
    • 1970-01-01
    • 2019-12-16
    相关资源
    最近更新 更多