我必须遵循一些JSON数据,这是一个大型JSON文件的片段。 我基本上只是想扩展这些数据。 我担心以后会将它添加到现有的JSON文件中。
JSON数据摘要是:
"Roles": [
{
"Role": "STACiWS_B",
"Settings": {
"HostType": "AsfManaged",
"Hostname": "JTTstSTBWS-0001",
"TemplateName": "W2K16_BETA_4CPU",
"Hypervisor": "sys2Director-pool4",
"InCloud": false
}
}
],
所以我想做的就是制作更多数据集" role" (缺乏更好的术语)
这样的事情:
"Roles": [
{
"Role": "Clients",
"Settings": {
"HostType": "AsfManaged",
"Hostname": "JTClients-0001",
"TemplateName": "Win10_RTM_64_EN_1511",
"Hypervisor": "sys2director-pool3",
"InCloud": false
}
},
{
"Role": "Clients",
"Settings": {
"HostType": "AsfManaged",
"Hostname": "JTClients-0002",
"TemplateName": "Win10_RTM_64_EN_1511",
"Hypervisor": "sys2director-pool3",
"InCloud": false
}
},
我开始使用一些看起来像这样的python代码,但是,似乎我还远远不够。
import json
import pprint
Roles = ["STACiTS","STACiWS","STACiWS_B"]
RoleData = dict()
RoleData['Role'] = dict()
RoleData['Role']['Setttings'] = dict()
ASFHostType = "AsfManaged"
ASFBaseHostname = ["JTSTACiTS","JTSTACiWS","JTSTACiWS_"]
HypTemplateName = "W2K12R2_4CPU"
HypPoolName = "sys2director"
def CreateASF_Roles(Roles):
for SingleRole in Roles:
print SingleRole #debug purposes
if SingleRole == 'STACiTS':
print ("We found STACiTS!!!") #debug purposes
NumOfHosts = 1
for NumOfHosts in range(20): #Hardcoded for STACiTS - Generate 20 STACiTS datasets
RoleData['Role']=SingleRole
RoleData['Role']['Settings']['HostType']=ASFHostType
ASFHostname = ASFBaseHostname + '-' + NumOfHosts.zfill(4)
RoleData['Role']['Settings']['Hostname']=ASFHostname
RoleData['Role']['Settings']['TemplateName']=HypTemplateName
RoleData['Role']['Settings']['Hypervisor']=HypPoolName
RoleData['Role']['Settings']['InCloud']="false"
CreateASF_Roles(Roles)
pprint.pprint(RoleData)
我一直收到这个令人困惑的错误,因为我认为字典可以命名索引。
Traceback (most recent call last):
File ".\CreateASFRoles.py", line 34, in <module>
CreateASF_Roles(Roles)
File ".\CreateASFRoles.py", line 26, in CreateASF_Roles
RoleData['Role']['Settings']['HostType']=ASFHostType
TypeError: string indices must be integers, not str
任何想法都表示赞赏。感谢。
答案 0 :(得分:1)
就在这里:
RoleData['Role']=SingleRole
将RoleData设置为字符串'STACiTS'。那么下一个命令的评估结果为:
'STACiTS'['Settings']['HostType']=ASFHostType
当然尝试使用另一个字符串索引到一个字符串,这是你的错误。字典可以有命名索引,但是你用字符串覆盖了你创建的字典。
您可能打算将RoleData [“Settings”]创建为字典然后分配给它,而不是RoleData [“Role”] [“Settings”]
另外请注意,此处还有其他语法错误:
RoleData['Role']['Setttings'] = dict()
错误拼写“设置”,以后可能会导致类似的问题,除非修复。