如何使用 boto3 读取包含多个词典的 JSON 文件
How to read JSON file containing multiple dictionaries with boto3
我有几个 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() 选项,但这也不起作用。我不想 to/can 不更改基础 json 文件并将字典存储在列表中。
如何使用 boto3 读取包含多个词典的 json 文件?
for line in f:
的 boto3 等价物是使用 iter_lines()
方法。
lines = obj.get()["Body"]
my_file = [json.loads(line) for line in lines.iter_lines()]
我有几个 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() 选项,但这也不起作用。我不想 to/can 不更改基础 json 文件并将字典存储在列表中。
如何使用 boto3 读取包含多个词典的 json 文件?
for line in f:
的 boto3 等价物是使用 iter_lines()
方法。
lines = obj.get()["Body"]
my_file = [json.loads(line) for line in lines.iter_lines()]