上传json到DynamoDB获取字符串错误

时间:2018-04-25 12:15:05

标签: python json amazon-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

1 个答案:

答案 0 :(得分:1)

当您将JSON字符串读入实体时,结果是一个dict,键为"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'键相关联的值。

你说它失败了#34;当你用2行跑时。&#34;最有可能的是,JSON应该被强制转换为字典列表,而不是单个字典。