首页 > 解决方案 > 将 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

标签: pythonjsonamazon-dynamodb

解决方案


当您将 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 应该真的被转换为字典列表,而不是单个字典。


推荐阅读