2015-12-02 62 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"列表之外,它只包含數字,字符串或布爾值等原子值。值列表可能包含嵌套結構,因爲我們只是在那裏移動引用。