2013-03-11 118 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'] 

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