Python 使用循环创建JSON格式
我正在为AWS DynamoDB创建一个表。所有关于如何使用所需JSON格式的文档都是完全手动演示的。。。在我的例子中,我想创建几个表,每个表都有几个列——当我知道我的列标题及其数据类型时,手动创建这些表似乎效率低下 boto3网站上有一个包含以下代码片段的指南:Python 使用循环创建JSON格式,python,loops,amazon-dynamodb,boto3,Python,Loops,Amazon Dynamodb,Boto3,我正在为AWS DynamoDB创建一个表。所有关于如何使用所需JSON格式的文档都是完全手动演示的。。。在我的例子中,我想创建几个表,每个表都有几个列——当我知道我的列标题及其数据类型时,手动创建这些表似乎效率低下 boto3网站上有一个包含以下代码片段的指南: # Get the service resource. dynamodb = boto3.resource('dynamodb') # Create the DynamoDB table. table = dynamodb.crea
# Get the service resource.
dynamodb = boto3.resource('dynamodb')
# Create the DynamoDB table.
table = dynamodb.create_table(
TableName='users',
KeySchema=[
{
'AttributeName': 'username',
'KeyType': 'HASH'
},
{
'AttributeName': 'last_name',
'KeyType': 'RANGE'
}
],
AttributeDefinitions=[
{
'AttributeName': 'username',
'AttributeType': 'S'
},
{
'AttributeName': 'last_name',
'AttributeType': 'S'
},
],
ProvisionedThroughput={
'ReadCapacityUnits': 5,
'WriteCapacityUnits': 5
}
)
现在我想知道,当然,如果您的数据中有数百个列/属性类型,您就不会想坐在那里全部输入。如何通过循环自动执行此过程?我有一个大致的想法,但我来自Java,我不太擅长思考这种情况下的解决方案
有人能帮忙吗?谢谢
编辑:
我把这个问题说得很糟糕,在文档中陷得太深,无法理解我在问什么。我想要一个解决方案,使用循环自动向DynamoDB表添加数据。我在下面的回答中进行了解释。当时我还不知道-我的问题中显示的代码片段只是关于定义密钥模式-即主/复合密钥。我想做的是将实际数据添加到表中——这些示例都是在boto3文档中手动完成的 回答我自己的问题:首先,您显然需要创建和定义密钥模式——这根本不是使用问题中显示的模板手动执行的时间 请注意,Boto3将不允许浮动值。。。我的解决方案是将它们更改为
str
类型。Boto3建议使用Decimal
,但Decimal(str(value))
不起作用,因为出于某种原因(有人能解释一下吗?)它被作为字符串Decimal(value)
传递:
这就是我如何使用pandas从excel导入数据,然后自动将数据放入我的表中:
#panda reads the excel document to extract df
df = pd.read_excel(fileRoute,dtype=object)
#the column headers are allocated to the keys variable
keys= df.columns.values
#create a dynamodb instance and link it to an existing table in dynamodb
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(name)
#batch_writer() allows the addition of many items at once to the table
with table.batch_writer() as batch:
dfvalues = df.values
#loop through values to generate dictionaries for every row in table
for sublist in dfvalues:
dicts = {}
for ind, value in enumerate(sublist):
if type(value) is float:
if math.isnan(value): #you might want to avoid 'NaN' types
continue
value = str(value) #convert float values to str
dicts[headings[ind]] = value
batch.put_item(
Item=dicts #add item to dynamoDB table
)
你试过什么?您在哪里可以看到要自动化的手动部分?您一直提到的JSON在哪里?