我有幾個 JSON 檔案,其中包含存盤在 S3中的多個字典。我需要訪問每一行并重命名一些鍵。我已經在我的本地環境中撰寫了完美運行的代碼,但是我在使用 Lambda 時遇到了問題。通常,我得到一個Expecting property name enclosed in double quotes錯誤。
示例 JSON:
{
"request": 123,
"key1": [
{
"timestamp_unix": 98321,
"key_2": "Portugal"
}
]
}
{
"request": 456,
"key1": [
{
"timestamp_unix": 35765,
"key_2": "China"
}
]
}
本地代碼:
import json
with open("myfile.json", "r") as f:
my_file = [json.loads(line) for line in f]
for j in my_file:
j[key1][0][key2] = j[key1][0].pop("key_2")
AWS 代碼:
import boto3
import json
s3 = boto3.resource("s3")
obj = s3.Object("my-bucket", "path_to/myfile.json")
json_string = obj.get()["Body"].read().decode("utf-8") # this is where my json object is read in with single quotes instead of double quotes
my_file = [json.loads(line) for line in json_string] # error error error
我也試過:
import boto3
import json
s3_client = boto3.client("s3")
obj = s3_client.get_object(Bucket="my-bucket", Key="path_to/myfile.json")
json_string = obj["Body"].read().decode() # this is where my json object is read in with single quotes instead of double quotes
my_file = [json.loads(line) for line in json_string] # error error error
我完全洗掉了 encode() 選項,但這也不起作用。我不想/不能更改底層 json 檔案并將字典存盤在串列中。
如何使用 boto3 讀取具有多個字典的 json 檔案?
uj5u.com熱心網友回復:
boto3 等價的for line in f:就是使用iter_lines()方法。
lines = obj.get()["Body"]
my_file = [json.loads(line) for line in lines.iter_lines()]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/405033.html
標籤:
