【问题标题】:Python manipulating json, lists, and dictionariesPython 处理 json、列表和字典
【发布时间】:2016-05-10 12:00:57
【问题描述】:

抱歉,篇幅较长,但尽量完整。

我正在尝试获取以下数据 - (仅从更大的 json 文件中抽取少量样本,结构相同)

{
    "count": 394,
    "status": "ok",
    "data": [
        {
            "md5": "cd042ba78d0810d86755136609793d6d",
            "threatscore": 90,
            "threatlevel": 0,
            "avdetect": 0,
            "vxfamily": "",
            "domains": [
                "dynamicflakesdemo.com",
                "www.bountifulbreast.co.uk"
            ],
            "hosts": [
                "66.33.214.180",
                "64.130.23.5",
            ],
            "environmentId": "1",
        },
        {
            "md5": "4f3a560c8deba19c5efd48e9b6826adb",
            "threatscore": 65,
            "threatlevel": 0,
            "avdetect": 0,
            "vxfamily": "",
             "domains": [
                "px.adhigh.net"
            ],
            "hosts": [
                "130.211.155.133",
                "65.52.108.163",
                "172.225.246.16"
            ],
            "environmentId": "1",
        }
    ]
}

如果“threatscore”超过 70,我想将它添加到这个 json 结构中 - 前任。 “数据”: [ { "md5": "cd042ba78d0810d86755136609793d6d", “威胁分数”:90,

{
"Event":
    {"date":"2015-11-25",
    "threat_level_id":"1",
    "info":"HybridAnalysis",
    "analysis":"0",
    "distribution":"0",
    "orgc":"SOC", 
    "Attribute": [
        {"type":"ip-dst",
        "category":"Network activity",
        "to_ids":True,
        "distribution":"3",
        "value":"66.33.214.180"},
        {"type":"ip-dst",
        "category":"Network activity",
        "to_ids":True,
        "distribution":"3",
        "value":"64.130.23.5"}
        {"type":"domain",
        "category":"Network activity",
        "to_ids":True,
        "distribution":"3",
        "value":"dynamicflakesdemo.com"},
        {"type":"domain",
        "category":"Network activity",
        "to_ids":True,
        "distribution":"3",
        "value":"www.bountifulbreast.co.uk"}
        {"type":"md5",
        "category":"Payload delivery",
        "to_ids":True,
        "distribution":"3",
        "value":"cd042ba78d0810d86755136609793d6d"}]
}
}

这是我的代码 -

from datetime import datetime
import os
import json
from pprint import pprint

now = datetime.now()

testFile = open("feed.json")
feed = json.load(testFile)


for x in feed['data']:
    if x['threatscore'] > 90:
        data = {}
        data['Event']={}
        data['Event']["date"] = now.strftime("%Y-%m-%d")
        data['Event']["threat_level_id"] = "1"
        data['Event']["info"] = "HybridAnalysis"
        data['Event']["analysis"] = 0
        data['Event']["distribution"] = 3
        data['Event']["orgc"] = "Malware"
        data['Event']["Attribute"] = []
        if 'hosts' in x:
            data['Event']["Attribute"].append({'type': "ip-dst"})
            data['Event']["Attribute"][0]["category"] = "Network activity"
            data['Event']["Attribute"][0]["to-ids"] = True
            data['Event']["Attribute"][0]["distribution"] = "3"
            data["Event"]["Attribute"][0]["value"] =x['hosts'] 
        if 'md5' in x:
            data['Event']["Attribute"].append({'type': "md5"})
            data['Event']["Attribute"][1]["category"] = "Payload delivery"
            data['Event']["Attribute"][1]["to-ids"] = True
            data['Event']["Attribute"][1]["distribution"]  = "3"
            data['Event']["Attribute"][1]['value'] = x['md5']
        if 'domains' in x:
            data['Event']["Attribute"].append({'type': "domain"})
            data['Event']["Attribute"][2]["category"] = "Network activity"
            data['Event']["Attribute"][2]["to-ids"] = True
            data['Event']["Attribute"][2]["distribution"] = "3"
            data['Event']["Attribute"][2]["value"] = x['domains']
        attributes = data["Event"]["Attribute"]
        data["Event"]["Attribute"] = []
        for attribute in attributes:
            for value in attribute["value"]:
                    if value == " ":
                        pass
                    else:
                        new_attr = attribute.copy()
                        new_attr["value"] = value
                        data["Event"]["Attribute"].append(new_attr)
        pprint(data)

with open('output.txt', 'w') as outfile:
    json.dump(data, outfile)

现在它似乎被清理了一点,但 data['md5'] 被拆分为每个字母,我认为就像 L3viathan 之前所说的那样,我一直在覆盖字典中的第一个元素......但我'不知道如何让它继续追加???

{'Event': {'Attribute': [{'category': 'Network activity',
                          'distribution': '3',
                          'to-ids': True,
                          'type': 'ip-dst',
                          'value': u'216.115.96.174'},
                         {'category': 'Network activity',
                          'distribution': '3',
                          'to-ids': True,
                          'type': 'ip-dst',
                          'value': u'64.4.54.167'},
                         {'category': 'Network activity',
                          'distribution': '3',
                          'to-ids': True,
                          'type': 'ip-dst',
                          'value': u'63.250.200.37'},
                         {'category': 'Payload delivery',
                          'distribution': '3',
                          'to-ids': True,
                          'type': 'md5',
                          'value': u'7'},
                         {'category': 'Payload delivery',
                          'distribution': '3',
                          'to-ids': True,
                          'type': 'md5',
                          'value': u'1'},

最后仍然出现以下错误: 回溯(最近一次通话最后): 文件“hybridanalysis.py”,第 34 行,在 data['Event']["Attribute"][1]["category"] = "Payload delivery" IndexError: 列表索引超出范围

最终目标是设置它,以便我可以将事件发布到 MISP,但它们必须一次一个。

【问题讨论】:

  • 重新考虑,我认为您的实际问题是您读取数据中的某些内容,然后每次threatscore 高于70时覆盖它。
  • 嘿L3viathan!我认为这与您所说的完全一样,但是我如何避免覆盖它而只是让它在继续通过 for 循环时附加另一个“事件”。
  • 将数据更改为列表,您可以在循环之外定义该列表。在循环中,只需附加一个新的事件字典。

标签: python arrays json list dictionary


【解决方案1】:

在 json 中,"Attiribute" 包含一个列表的值,其中包含一个 1 项,一个字典,如下所示。

{'Event': {'Attribute': [{'category': 'Network activity',
                      'distribution': '3',
                      'to-ids': True,
                      'type': 'ip-dst',
                      'value': [u'54.94.221.70']}]
...

当您调用 data['Event']["Attribute"][1]["category"] 时,您将获得属性列表中的第二项(索引 1),而它只有一项,这就是您收到错误的原因。

【讨论】:

    【解决方案2】:

    我认为这应该可以解决您的问题。我一口气添加了属性字典,并将数据移动到列表中(这更合适),但您可能希望删除包装事件的多余列表。

    from datetime import datetime
    import os
    import json
    from pprint import pprint
    
    now = datetime.now()
    
    testFile = open("feed.json")
    feed = json.load(testFile)
    
    data_list = []
    
    for x in feed['data']:
        if x['threatscore'] > 90:
            data = {}
            data['Event']={}
            data['Event']["date"] = now.strftime("%Y-%m-%d")
            data['Event']["threat_level_id"] = "1"
            data['Event']["info"] = "HybridAnalysis"
            data['Event']["analysis"] = 0
            data['Event']["distribution"] = 3
            data['Event']["orgc"] = "Malware"
            data['Event']["Attribute"] = []
            if 'hosts' in x:
                data['Event']["Attribute"].append({
                    'type': 'ip-dst',
                    'category': 'Network activity',
                    'to-ids': True,
                    'distribution': '3',
                    'value': x['hosts']})
            if 'md5' in x:
                data['Event']["Attribute"].append({
                    'type': 'md5',
                    'category': 'Payload delivery',
                    'to-ids': True,
                    'distribution': '3',
                    'value': x['md5']})
            if 'domains' in x:
                data['Event']["Attribute"].append({
                    'type': 'domain',
                    'category': 'Network activity',
                    'to-ids': True,
                    'distribution': '3',
                    'value': x['domains']})
            attributes = data["Event"]["Attribute"]
            data["Event"]["Attribute"] = []
            for attribute in attributes:
                for value in attribute["value"]:
                        if value == " ":
                            pass
                        else:
                            new_attr = attribute.copy()
                            new_attr["value"] = value
                            data["Event"]["Attribute"].append(new_attr)
            data_list.append(data)
    
    with open('output.txt', 'w') as outfile:
        json.dump(data_list, outfile)
    

    【讨论】:

    • L3viathan Grazi!!!!你有 data ={} 是'scratch'字典的名称,这并不重要,因为该名称不会出现在最终的 json 结构中。在数据内部创建 data['Event']={} ,您可以在其中添加 json,它基本上是一个字典,所以只需输入它 - data['Event']["info"] = "HybridAnalysis" 哪个与发布所需的结构相匹配。属性你 .append 因为那是一个列表,我们将字典作为列表的一部分附加。我不明白为什么 MD5 仍然被拆分成单独的字符??
    • 换句话说,为什么它将“MD5”拆分为单个字符,而不是对“主机”和“域”做完全相同的事情?它在逗号上正确拆分这些列表。
    • @mathurin68 啊,我明白了。因为它正在迭代该值。如果你遍历一个列表(比如域或主机),你会得到字符串。如果你遍历字符串,你会得到单字符的字符串。
    【解决方案3】:

    感谢 L3viathan!下面是我如何调整它以不迭代 MD5。

        attributes = data["Event"]["Attribute"]
        data["Event"]["Attribute"] = []
        for attribute in attributes:
            if attribute['type'] == 'md5':
                new_attr = attribute.copy()                        
                new_attr["value"] = str(x['md5'])
                data["Event"]["Attribute"].append(new_attr)
            else:
                for value in attribute["value"]:
                    new_attr = attribute.copy()                        
                    new_attr["value"] = value
                    data["Event"]["Attribute"].append(new_attr)
        data_list.append(data)
    

    操作 json 似乎是学习列表和字典的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-01
      • 2021-03-12
      • 1970-01-01
      • 2020-03-23
      • 2020-05-20
      • 2023-01-14
      • 1970-01-01
      • 2013-02-23
      相关资源
      最近更新 更多