python 字典/json 初始

标签 python arrays json dictionary

如何在字典内提取、拆分和追加数组?

这是我得到的数据:

data = {
    "Event":{
        "distribution":"0",
        "orgc":"Oxygen",
        "Attribute": [{
            "type":"ip-dst",
            "category":"Network activity",
            "to_ids":"true",
            "distribution":"3",
            "value":["1.1.1.1","2.2.2.2"]
        }, {
            "type":"url",
            "category":"Network activity",
            "to_ids":"true",
            "distribution":"3",
            "value":["msn.com","google.com"]
        }]
    }
}

这就是我需要的——

{
    "Event": {
        "distribution": "0",
        "orgc": "Oxygen",
        "Attribute": [{
                "type": "ip-dst",
                "category": "Network activity",
                "to_ids": "true",
                "distribution": "3",
                "value": "1.1.1.1"
            }, {
                "type": "ip-dst",
                "category": "Network activity",
                "to_ids": "true",
                "distribution": "3",
                "value": "2.2.2.2"
            }, {
                "type": "url",
                "category": "Network activity",
                "to_ids": "true",
                "distribution": "3",
                "value": "msn.com"
            }, {
                "type": "url",
                "category": "Network activity",
                "to_ids": "true",
                "distribution": "3",
                "value": "google.com"
            }
        }
    }

这就是我刚刚玩弄它的地方,完全迷失了!!

for item in data["Event"]["Attribute"]:
    if "type":"ip-dst" and len("value")>1:
        if 'ip-dst' in item["type"] and len(item["value"])>1:
            for item in item["value"]:

...完全迷失了

最佳答案

这个怎么样?

#get reference to attribute dict
attributes = data["Event"]["Attribute"]
#in the event dictionary, replace it with an empty list
data["Event"]["Attribute"] = []

for attribute in attributes:
    for value in attribute["value"]:
        #for every value in every attribute, copy that attribute
        new_attr = attribute.copy()
        #set the value to that value
        new_attr["value"] = value
        #and append it to the attribute list
        data["Event"]["Attribute"].append(new_attr)

这将适用于您所显示的数据结构,但不一定适用于所有类型的嵌套数据,因为我们对属性进行了浅复制。这意味着您必须确保除了 "value" 列表之外,它仅包含原子值,例如数字、字符串或 bool 值。值列表可能包含嵌套结构,因为我们只是将引用移动到那里。

关于python 字典/json 初始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34053223/

相关文章:

python - 如何用pyfits合并两个表?

javascript - 将 Javascript 对象和子对象转换为对象数组 - lodash

arrays - 2 个未排序的数组,查找是否有任何一对值加起来等于目标?

java - 获取列表的 ArrayIndexOutOfBoundsException

javascript - 如何摆脱许多IF并使系统具有不同的元素?

python - 平均 numpy 数组但保持形状

python - 使用 Python 驱动程序检查 Cassandra 表中是否存在记录

c# - JSON.net(反)序列化未类型化的属性

python - 在 Python 中使用 open 函数和循环

python - 如何使用 Django 发送/获取 JSON 对象?