使用Python boto3从S3读取JSON文件 [英] Reading an JSON file from S3 using Python boto3

查看:964
本文介绍了使用Python boto3从S3读取JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在S3存储桶测试"中一直遵循JSON

I kept following JSON in S3 bucket 'test'

{
  'Details' : "Something" 
}

我正在使用以下代码读取此JSON并打印键"Details"

I am using following code to read this JSON and printing the key 'Details'

s3 = boto3.resource('s3',
                    aws_access_key_id=<access_key>,
                    aws_secret_access_key=<secret_key>
                    )
content_object = s3.Object('test', 'sample_json.txt')
file_content = content_object.get()['Body'].read().decode('utf-8')
json_content = json.loads(repr(file_content))
print(json_content['Details'])

并且由于字符串索引必须为整数" ,我收到了错误消息 我不想从S3下载文件然后阅读.

And i am getting error as 'string indices must be integers' I don't want to download the file from S3 and then reading..

推荐答案

如上所述,必须删除repr,并且json文件必须使用双引号属性.在aws/s3上使用此文件:

As mentioned in the comments above, repr has to be removed and the json file has to use double quotes for attributes. Using this file on aws/s3:

{
  "Details" : "Something"
}

和以下Python代码,它可以正常工作:

and the following Python code, it works:

import boto3
import json

s3 = boto3.resource('s3')

content_object = s3.Object('test', 'sample_json.txt')
file_content = content_object.get()['Body'].read().decode('utf-8')
json_content = json.loads(file_content)
print(json_content['Details'])
# >> Something

这篇关于使用Python boto3从S3读取JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆