2015-12-02 63 views
1

如何在字典内的字典内拉出,拆分和追加数组?python字典/ json开始

这是我已经得到了数据:

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"]: 

...并完全丧失

+0

除了选项卡,有什么区别? – jonrsharpe

+1

不知道你在这里问什么。 “得到”和“需要”看起来像相同的结构。你是否试图将字典转换为json? –

+0

@MadWombat OP正试图从组合的“属性”值合并为单个值。 – Tomalak

回答

2

这个怎么样?

#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"列表之外,它只包含数字,字符串或布尔值等原子值。值列表可能包含嵌套结构,因为我们只是在那里移动引用。