【问题标题】:Read a JSON from S3从 S3 读取 JSON
【发布时间】:2020-07-29 12:18:41
【问题描述】:

我是 python 新手,并遵循 existing_post 的答案,我正在尝试从 amazon S3 读取 json 文件,如下所示:

  import boto3
  import os
    BUCKET = 'my_bucket'
    FILE_TO_READ = 'file.json'
    client = boto3.client('s3',
                           aws_access_key_id=os.environ.my_key,
                           aws_secret_access_key=os.environ.my_secret_key
                         )
    result = client.get_object(Bucket=BUCKET, Key='file') 
    text = result["Body"].read().decode()
    print(text['key']) # Use your desired JSON Key for your value  

但是我收到以下错误:

NoSuchKey: An error occurred (NoSuchKey) when calling the GetObject operation: The specified key does not exist.

谁能告诉我我做错了什么?

【问题讨论】:

    标签: python amazon-s3


    【解决方案1】:

    错误是说您的密钥不存在。我看到您已经拥有密钥“file.json”,所以我认为它存在。我会假设您已像 bucket/same_file/file.json 一样存储您的文件。如果是这种情况,试试这个:

    import json
    import boto3
    s3_obj =boto3.client('s3')
    s3_clientobj = s3_obj.get_object(Bucket='your_bucket', Key='file/file.json')
    s3_clientdata = s3_clientobj['Body'].read().decode('utf-8')
    print("printing s3_clientdata")
    print(s3_clientdata)
    

    如果你想做数据操作,一个更 Pythonic 的解决方案是:

    fs = s3fs.S3FileSystem()
    with fs.open('yourbucket/file/your_json_file.json', 'rb') as f:
        s3_clientdata = json.load(f)
    #Convert to df
    df = pd.DataFrame(s3_clientdata,index=[0])
    

    【讨论】:

      【解决方案2】:

      我看到您正在检索带有关键“文件”的对象

      result = client.get_object(Bucket=BUCKET, Key='file')
      

      我认为你的意思是:

      result = client.get_object(Bucket=BUCKET, Key=FILE_TO_READ)
      

      更多详情请参阅get_object reference

      【讨论】:

      • 错误提示“指定的密钥不存在”。尝试:亚马逊控制台 > S3 > 您的存储桶 > 单击您要下载的文件 > 概览 > 密钥。您应该尝试使用该键
      猜你喜欢
      • 2020-12-13
      • 1970-01-01
      • 2017-04-21
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 2019-09-22
      • 1970-01-01
      相关资源
      最近更新 更多