python - 将 json 上传到 DynamoDB 得到字符串错误
问题描述
我的 Json 文件包含以下行:
{
"tenant_EntityID": {
"s": "12345"
},
"enrtyDate": {
"s": "7.9.2000 14:53:45"
},
"first_name": {
"s": "Y7M9"
},
"last_name": {
"s": "NUYE"
},
"gender": {
"s": "male"
},
"birth_incorp_date": {
"s": "9.3.1999 14:49:44"
},
"email": {
"s": "0XPY9E@C20R.com"
}
}
当我尝试通过以下代码将其加载到 DynamoDB 时:
import boto3
import json
import decimal
dynamodb = boto3.resource('dynamodb', region_name='us-west-2')
table = dynamodb.Table('Entities')
with open("C:/data/bigJson1.json") as json_file:
Entities = json.load(json_file, parse_float = decimal.Decimal)
for Entity in Entities:
table.put_item(
Item={
'tenant_EntityID':Entity['tenant_EntityID'] ,
'enrtyDate': Entity['enrtyDate'],
'first_name': Entity['first_name'],
'last_name': Entity['last_name'],
'gender': Entity['gender'],
'birth_incorp_date': Entity['birth_incorp_date'],
'email': Entity['email']
}
)
我收到错误消息:
Traceback (most recent call last):
File "C:/Freedom/Comparing json file.py", line 39, in <module>
'tenant_EntityID':Entity['tenant_EntityID'] ,
TypeError: string indices must be integers
解决方案
当您将 JSON 字符串读入实体时,结果是一个字典,带有键"tenant_EntityID"
等。该语句for Entity in Entities
遍历该字典,为您提供字典的键,它们是字符串。
看起来你需要更像这样的东西:
import boto3
import json
import decimal
dynamodb = boto3.resource('dynamodb', region_name='us-west-2')
table = dynamodb.Table('Entities')
with open("C:/data/bigJson1.json") as json_file:
Entity = json.load(json_file, parse_float = decimal.Decimal)
table.put_item(
Item={
'tenant_EntityID':Entity['tenant_EntityID'] ,
'enrtyDate': Entity['enrtyDate']['s'],
'first_name': Entity['first_name']['s'],
'last_name': Entity['last_name']['s'],
'gender': Entity['gender']['s'],
'birth_incorp_date': Entity['birth_incorp_date']['s'],
'email': Entity['email']
}
)
这只是我自己的猜测,您想要与's'
键关联的值。
您说“当您运行 2 行时”它会失败。很可能 JSON 应该真的被转换为字典列表,而不是单个字典。
推荐阅读
- php - 为什么这个 mysql_ 函数在 PHP 中未定义?
- html - 加载默认幻灯片的更简单方法(使用 css :target)
- git - 如何从提交中只挑选特定的文件类型
- java - 扩展 javafx.scene.shape.Circle 的类的 InvocationTargetException
- asp.net-web-api - OData-query is throwing error for $expand query
- google-sheets - Attendance marking/counting issue, Google Sheets
- ssis - 在 SSIS 任务中避免 Jade Db 源连接超时
- python-2.7 - 我不明白错误的含义是什么
- python - 如何将浏览器返回的json对象转换为python lambda函数中的字符串
- javascript - 使用参数设置状态