2016-11-03 169 views
0

我有一個看起來像這樣的結構,其具有在它的字典:枚舉使用python

{ 
"permutations": [ 
    { 
     "testname": "Test1", 
     "file_type": "file1", 
     "test_options": { 
      "rule_entities": [ 
       "name1" 
     ], 
     }, 
     ], 
     "userType": "user", 
     "rulename": "rule1", 
     "action": "alert", 
     }, 
    { 
     "testname": "Test2", 
     "file_type": "file2", 
     "test_options": { 
      "rule_entities": [ 
       "name2" 
      ], 
     }, 
     ], 
     "userType": "user", 
     "rulename": "rule2", 
     "action": "alert", 
     } 
} 

我想通過追加,使在上述結構測試名和RuleName中的變化都與rule_entities值,變量testname:「Test1_name1」和rulename:「rule1_name1」,其中name1來自rule_entities數組。因此,上述結構應該是最終的結構

{ 
"permutations": [ 
    { 
     "testname": "Test1_name1", 
     "file_type": "file1", 
     "test_options": { 
      "rule_entities": [ 
       "name1" 
     ], 
     }, 
     ], 
     "userType": "user", 
     "rulename": "rule1_name1", 
     "action": "alert", 
     }, 
    { 
     "testname": "Test2_name2", 
     "file_type": "file2", 
     "test_options": { 
      "rule_entities": [ 
       "name2" 
      ], 
     }, 
     ], 
     "userType": "user", 
     "rulename": "rule2_name2", 
     "action": "alert", 
     } 
} 

我使用下面的代碼給它一個嘗試snipet

for index, d in enumerate['permutations']: 
    testname = d['permutations'][index]['testname'] 
    testname_new = testname + '_' + rule_entitities 


for index, d in enumerate['permutations']: 
    rulename = d['permutations'][index]['rulename'] 
    rulename_new = rulename + '_' + rule_entities 

我沒有得到期望的輸出。提前致謝!!

+0

我餵你的JSON到http:// codebeautify .org/jsonviewer並被抱怨說它不是有效的JSON –

回答

1

你永遠不更新存儲在字典

for index, d in enumerate['permutations']: 
    testname = d['permutations'][index]['testname'] 
    testname_new = testname + '_' + rule_entities 
    d['permutations'][index]['testname'] = testname_new 


for index, d in enumerate['permutations']: 
    rulename = d['permutations'][index]['rulename'] 
    rulename_new = rulename + '_' + rule_entities 
    d['permutations'][index]['rulename'] = rulename_new 
0

我得到它的工作使用下面的代碼值:

for x in 'permutations': 
    rule_entity_slash = ['permutations'][0]['test_options']['rule_entities'][0] 
    rule_entity_underscore = rule_entity_slash.replace("/","_") 
    x['testname'] = x['testname'] + '_' + rule_entity_underscore 
    x['rulename'] = x['rulename'] + '_' + rule_entity_underscore 

感謝