如何创建一个json字符串来传递它ot create_table()

时间:2017-04-19 05:57:32

标签: python json boto

对于boto的create_table函数,我想要跟随字符串

'AttributeDefinitions': [{'AttributeName': 'Id','AttributeType': 'N'},{'AttributeName': 'orgId','AttributeType': 'S'}]

'KeySchema': [{'AttributeName': 'orgId','KeyType': 'HASH'},{'AttributeName': 'Id','KeyType': 'RANGE'}]

'ProvisionedThroughput': {'ReadCapacityUnits': 1,'WriteCapacityUnits': 1}

我想用变量替换值,我尝试了以下方法,但它没有用。

attribute_definition="'AttributeDefinitions': [{'AttributeName':"+hash_attribute_name+",'AttributeType':"+hash_attribute_type+"},{'AttributeName': "+range_attribute_name+",'AttributeType': "+range_attribute_type+"}]"

key_schema="'KeySchema': [{'AttributeName': "+hash_attribute_name+",'KeyType': 'HASH'},{'AttributeName': "+hash_attribute_type+",'KeyType': 'RANGE'}]"

capacity="'ProvisionedThroughput': {'ReadCapacityUnits': "+read_capacity+",'WriteCapacityUnits': "+write_capacity+"}"

然后我尝试创建如下列表。

attribute_definition={'AttributeDefinitions': [{'AttributeName':hash_attribute_name,'AttributeType':hash_attribute_type},{'AttributeName': range_attribute_name,'AttributeType': range_attribute_type}]}

key_schema={'KeySchema': [{'AttributeName': hash_attribute_name,'KeyType': 'HASH'},{'AttributeName': hash_attribute_type,'KeyType': 'RANGE'}]}

capacity={'ProvisionedThroughput': {'ReadCapacityUnits': read_capacity,'WriteCapacityUnits': write_capacity}

抛出以下错误:print ("attribute_definition") ^ SyntaxError: invalid syntax

我尝试使用json.loads()将字符串转换为json

attribute_definition=json.loads("{'AttributeDefinitions': [{'AttributeName':"+hash_attribute_name+",'AttributeType':"+hash_attribute_type+"},{'AttributeName': "+range_attribute_name+",'AttributeType': "+range_attribute_type+"}]}")

key_schema=json.loads("{'KeySchema': [{'AttributeName': "+hash_attribute_name+",'KeyType': 'HASH'},{'AttributeName': "+hash_attribute_type+",'KeyType': 'RANGE'}]}")

capacity=json.loads("{'ProvisionedThroughput': {'ReadCapacityUnits': "+read_capacity+",'WriteCapacityUnits': "+write_capacity+"}}")

发现以下错误:ValueError: Expecting property name: line 1 column 2 (char 1)

我想将此字符串或列表传递给create_table函数以创建表。

任何人都可以帮助我如何实现它。

1 个答案:

答案 0 :(得分:0)

你试过json.dumps吗?

    >>> hash_attribute_name = 'Id'
    >>> hash_attribute_type = 'N'
    >>> range_attribute_name = 'orgId'
    >>> range_attribute_type = 'S'
    >>> attribute_definition={'AttributeDefinitions':[{'AttributeName':hash_attribute_name,'AttributeType':hash_attribute_type},{'AttributeName': range_attribute_name,'AttributeType': range_attribute_type}]}
    >>> attribute_definition
    {'AttributeDefinitions': [{'AttributeName': 'Id', 'AttributeType': 'N'}, {'AttributeName': 'orgId', 'AttributeType': 'S'}]}
    >>> import json
    >>> json.dumps(attribute_definition)
    '{"AttributeDefinitions": [{"AttributeName": "Id", "AttributeType": "N"}, {"AttributeName": "orgId", "AttributeType": "S"}]}'