我有要在Python中解析的JSON,看起来像这样
{
"New Slim Testing":{
"name":"New Slim Testing",
"id":"6496",
"type":1,
"fullpath":"\\New Slim Testing",
"children": {
"sf_account":{
"name":"sf_account",
"type":1,
"fullpath":"",
"id":"6516"
},
"sf_case":{
"name":"sf_case",
"type":1,
"fullpath":"",
"id":"6517",
"children": {
"sf_case_delete":{
"name":"sf_case_delete",
"type":1,
"fullpath":"",
"id":"6518"
}
}
},
"sync_incr_sfdc_b2b_to_rds_sf_case":{
"name":"sync_incr_sfdc_b2b_to_rds_sf_case",
"type":2,
"fullpath":"",
"command":"<T4I_DNA_SCRIPTS.23>run_infacloud_task.ksh",
"parameters":"0 <JobName> DSS",
"id":"6520"
}
}
}
}
此JSON将用于进行API调用。尽管id目前是硬编码的,但它应该是动态的,并由API调用返回。迭代时如何更改此字典中的某些值?
例如:将创建父作业,将为其分配一个ID,创建子作业时,我将使用其父ID等。
对于全路径字段也是如此。我想在运行时派生它(迭代字典),而不是对其进行硬编码。
这就是我想要做的
def jsonTraverser(json,parentJson):
templateXML = settings.JOBXMLTEMPLATE
for key, val in json.items():
if isinstance(val, dict):
pp = pprint.PrettyPrinter(indent=2)
if(key!="children"):
parentId = parentJson["id"]
fullpath = '{}\\{}'.format(parentJson["fullpath"],json[key]["name"])
print('Fullpath is {}'.format(fullpath))
json['fullpath'] = fullpath
if val['type']==1:
print('Creating job group {}'.format(val["name"]))
createJob(val,parentId)
else:
print('Creating job {}'.format(val["name"]))
createJob(val,parentId)
jsonTraverser(val,json)
我遇到了错误:字典在迭代过程中更改了大小
答案 0 :(得分:0)
通过list(dct.keys())
使用json数据的独立键(列表适用于python3 +):
In [5]: dct = {1: 2, 2: 3}
In [6]: for k in list(dct.keys()):
...: dct[str(k)] = dct[k]
...:
In [7]: dct
Out[7]: {1: 2, 2: 3, '1': 2, '2': 3}