[英]How to read S3 file in Lambda function(in python)
I am trying to read a file from S3, which has the following content stored in it:我正在尝试从 S3 读取一个文件,其中存储了以下内容:
{"empID":{"n":"7"},"name":{"s":"NewEntry"}}
{"empID":{"n":"3"},"name":{"s":"manish"}}
{"empID":{"n":"2"},"name":{"s":"mandeep"}}
{"empID":{"n":"4"},"name":{"s":"Vikas"}}
{"empID":{"n":"1"},"name":{"s":"babbar"}}
I want to iterate over each and every object and do some some processing on them.我想遍历每个对象并对它们进行一些处理。
I am taking reference from this code:我正在参考这段代码:
import json
import boto3
s3_obj =boto3.client('s3')
s3_clientobj = s3_obj.get_object(Bucket='dane-fetterman-bucket', Key='mydata.json')
s3_clientdata = s3_clientobj['Body'].read().decode('utf-8')
print("printing s3_clientdata")
print(s3_clientdata)
print(type(s3_clientdata))
s3clientlist=json.loads(s3_clientdata)
print("json loaded data")
print(s3clientlist)
print(type(s3clientlist))
but there is not any "Body" attribute in the file.但文件中没有任何“Body”属性。 Can i get some points to do the desired stuff.
我可以得到一些积分来做想要的东西吗?
The issue is that the file actually contains individual JSON on each line, rather than being a complete JSON object itself.问题是该文件实际上在每一行都包含单独的 JSON,而不是一个完整的 JSON 对象本身。
Therefore, the program needs to process each line independently:因此,程序需要独立处理每一行:
import json
import boto3
s3_client = boto3.client('s3')
s3_clientobj = s3_client.get_object(Bucket='my-bucket', Key='mydata.json')
for line in s3_clientobj['Body'].iter_lines():
object = json.loads(line)
print(f"ID: {object['empID']['n']} Name: {object['name']['s']}")
Alternatively, you could download the whole object to disk, then just use normal for line in open('file'):
syntax.或者,您可以将整个对象下载到磁盘,然后
for line in open('file'):
语法中使用 normal for line in open('file'):
。
See also: Read a file line by line from S3 using boto?另请参阅:使用 boto 从 S3 逐行读取文件?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.