2013-03-11 159 views
0

有人可以提供一個如何循環通過python中的這個對象的例子,並拉出'價值'其中api = 'interesting'arguments.name = 'FileName'Python對象迭代

這是我到目前爲止所。
該對象有更多的進程和調用....輸出已被省略。

編輯:我要指出,我正在運行此代碼時出現以下錯誤: 「類型錯誤:列表索引必須是整數,而不是STR」

for k, v in object['behavior']['processes']['calls'].items(): 
      if v['api'] == "interesting": 
          <loop through arguments next> 

對象:

{"behavior": { 
    "processes": [ 
     { 
     "parent_id": "312", 
     "process_name": "test.exe", 
     "process_id": "1184", 
     "first_seen": "2013-03-02 17:22:48,359", 
     "calls": [ 
      { 
      "category": "filesystem", 
      "status": "FAILURE", 
      "return": "0xc000003a", 
      "timestamp": "2013-03-02 17:22:48,519", 
      "thread_id": "364", 
      "repeated": 0, 
      "api": "interesting", 
      "arguments": [ 
       { 
       "name": "FileHandle", 
       "value": "0x00000000" 
       }, 
       { 
       "name": "DesiredAccess", 
       "value": "0x80100080" 
       }, 
       { 
       "name": "FileName", 
       "value": "c:\\cgvi5r6i\\vgdgfd.72g" 
       }, ... 
+1

繼續開展工作是怎麼回事? – lxop 2013-03-11 03:00:52

回答

1

你在問題中提供的作爲初學者的內容不起作用,因爲你沒有遍歷列表中的元素,它們分別是鍵值爲"processes""calls"的值。也就是說,你需要更多的東西一樣

for proc in object ['processes']: 
    for call in proc ['calls']: 
     if call ['api'] == "interesting": 
      fname = None 
      for arg in call ['arguments']: 
       if arg ['name'] == "FileName": 
        fname = arg ['value'] 

然後你要找的文件名會在fname。這沒有錯誤檢查,因爲我不知道你的數據來自哪裏。

+0

提供輸入的每個人都是正確的,但最終我最終使用此代碼。非常感謝你。 – Mike 2013-03-11 23:45:51

1

你在做什麼似乎沒問題, 但

  1. 您的索引是o ff(仔細看清單有
  2. 您的支票似乎無效(v是一個字符串,所以v['api']是無效的)。

因此,嘗試這樣做,而不是,(我已經採取了你的對象爲i

for k, v in i['behavior']['processes'][0]['calls'][0].items(): 
    if k == 'api' and v == "interesting": 
     print k,v 

OR

for dct in i['behavior']['processes'][0]['calls']: 
    if dct['api'] == "interesting": 
     print 'api',dct['api'] 

OR

for dct in i['behavior']['processes'][0]['calls']: 
    for k,v in dct.items(): 
     if k == 'api' and v =="interesting": 
      print 'api',dct['api'] 

,或者如果有是每個列表的多個部分,

for proc in i['behavior']['processes']: 
    for call in proc['calls']: 
     print 'api =>',call['api'] # a if here 
     for args in call['arguments']: 
      print ' argument.name =>',args['name'] # and another if here should do the trick. 

爲什麼你的錯誤
試試下面的一段代碼,你就會明白你在做什麼錯

print type(i['behavior']['processes']) 
print type(i['behavior']['processes'][0]) 
print type(i['behavior']['processes'][0]['calls']) 
print type(i['behavior']['processes'][0]['calls'][0]) 
+0

如果帖子是有用的,你應該upvote他們... – pradyunsg 2013-03-12 02:41:35

0
object['behavior']['processes']['calls'] 

是一個列表,而不是字典。