Python对象迭代

时间:2013-03-11 02:58:03

标签: python

有人可以举例说明如何在python中循环遍历此对象,并在api = 'interesting'arguments.name = 'FileName'中提取“值”吗?

到目前为止,这是我所拥有的 这个对象有更多的进程和调用....输出已被省略。

编辑:我应该提到运行此代码时出现以下错误: “TypeError:list indices必须是整数,而不是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"
                }, ...

3 个答案:

答案 0 :(得分:1)

你在做什么似乎没问题, 但是

  1. 您的索引已关闭(仔细查看列表
  2. 您的支票似乎无效(v是一个字符串,因此v['api']无效)。
  3. 所以,试着这样做,(我把你的对象当作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])
    

答案 1 :(得分: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。这没有错误检查,因为我不知道你的数据来自哪里。

答案 2 :(得分:0)

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

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