簡體   English   中英

遍歷從 S3 下載的 json 文件中的對象數組

[英]Looping through array of objects in json file downloaded from S3

我正在使用 boto3 get_object 從 S3 獲取一個 json 文件。 我需要從文件中獲取內容並遍歷對象數組並一次獲取一個 object。 當我循環時,我每次迭代得到一個字符。

導入 json 導入 boto3

s3 = boto3.client('s3') session = boto3.Session()

def lambda_handler(event, context):
    bucket = event["bucket"]
    key = event["key"]

    data = s3.get_object(Bucket=bucket, Key=key)
    contents = data['Body'].read()

    test = contents.decode("utf-8")

    # convert contents to native python string representing json object
    s3_string = json.dumps(contents.decode("utf-8"))

    # return dict
    s3_dict = json.loads(s3_string)

    # this seems to output valid json
    # print(str(s3_dict))

    for item in s3_dict:
        print(item)

文件中的json格式如下

[{
        "location": "123 Road Dr",
        "city_state": "MyCity ST",
        "phone": "555-555-5555",
        "distance": "1"
    },
    {
        "location": "456 Avenue Crt",
        "city_state": "MyTown AL",
        "phone": "555-867-5309",
        "distance": "0"
    }
]

這就是我得到的(每次迭代一個字符)...

  1. [
  2. {
  3. “……

這就是我需要的(json 格式)...

第一個循環

{
        "location": "123 Road Dr",
        "city_state": "MyCity ST",
        "phone": "555-555-5555",
        "distance": "1"
    }

第二循環

 {
        "location": "456 Avenue Crt",
        "city_state": "MyTown AL",
        "phone": "555-867-5309",
        "distance": "0"
    }

有人可以告訴我哪里出錯了嗎?

提前致謝。

這是可行的解決方案。

def lambda_handler(event, context):
    bucket = event["bucket"]
    key = event["key"]

    data = s3.get_object(Bucket=bucket, Key=key)
    contents = data['Body'].read()

    # convert contents to native python string representing json object
    s3_string = contents.decode("utf-8")

    # check the "type" of s3_string - in this case it is <class 'str'>
    print("s3_string is " + str(type(s3_string)))

    # return python list
    s3_list = json.loads(s3_string)

    # check the "type" of s3_list - in this case it is <class 'list'>
    print("s3_list is " + str(type(s3_list)))

    # this returns valid json for every object in the array in original json file.
    for item in s3_list:
        print(json.dumps(item)) 

我假設我在 json.loads 的默認行為中得到了 python 字典。 我實際上得到了一份清單。 這解釋了為什么... Json 文件作為列表而不是字典加載。 使用 python

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM