2017-06-15 59 views
0

這是我的JSON文件的樣本:從JSON文件過濾出所需的數據(Python)的

{ 
"pops": [{ 
     "name": "pop_a", 
     "subnets": { 
      "Public": ["1.1.1.0/24,2.2.2.0/24"], 
      "Private": ["192.168.0.0/24,192.168.1.0/24"], 
     "more DATA":"" 
     } 
    }, 
    { 
     "name": "pop_b", 
     "subnets": { 
      "Public": ["3.3.3.0/24,4.4.4.0/24"], 
      "Private": ["192.168.2.0/24,192.168.3.0/24"], 
     "more DATA":"" 
     } 
    } 
] 
} 

後,我讀它,我想打一個DIC對象和存儲的一些事情,我需要從這個文件。 我希望我的對象是這樣..

[{ 
    "name": "pop_a", 
    "subnets": {"Public": ["1.1.1.0/24,2.2.2.0/24"],"Private": ["192.168.0.0/24,192.168.1.0/24"]} 
}, 
{ 
    "name": "pop_b", 
    "subnets": {"Public": ["3.3.3.0/24,4.4.4.0/24"],"Private": ["192.168.2.0/24,192.168.3.0/24"]} 
}] 

的話,我希望能夠進入一些公共/私有值的

這裏是我想,我知道有更新( ),這也給了同樣的不想要的結果

def my_funckion(): 
    nt_json = [{'name':"",'subnets':[]}] 
    Pname = [] 
    Psubnet= [] 

    for pop in pop_json['pops']: # it print only the last key/value 
     nt_json[0]['name']= pop['name'] 
     nt_json[0]['subnet'] = pop['subnet'] 
    pprint (nt_json) 

    for pop in pop_json['pops']: 
    """ 
    it print the names in a row then all of the ipss 
    """ 
    Pname.append(pop['name']) 
    Pgre.append(pop['subnet']) 
    nt_json['pop_name'] = Pname 
    nt_json['subnet']= Psubnet 
    pprint (nt_json) 
+0

你究竟想要輸出明智嗎?你得到了什麼 – depperm

+0

你不需要格式化JSON文件後,將其導入到變量。只需使用for循環找到您想要的密鑰即可。然後使用嵌套for循環來查找嵌套字典中的鍵。 –

+0

第二個數據結構看起來非常像我的第一個數據結構 - 所以,你需要改變什麼? –

回答

1

setdefault()下面是一個使用列表中理解一個快速的解決方案。請注意,只有在有足夠的json結構知識的情況下才能採用這種方法。

>>> import json 
>>> 
>>> data = ... # your data 
>>> new_data = [{ "name" : x["name"], "subnets" : {"Public" : x["subnets"]["Public"], "Private" : x["subnets"]["Private"]}} for x in data["pops"]] 
>>> 
>>> print(json.dumps(new_data, indent=2)) 
[ 
    { 
    "name": "pop_a", 
    "subnets": { 
     "Private": [ 
     "192.168.0.0/24,192.168.1.0/24" 
     ], 
     "Public": [ 
     "1.1.1.0/24,2.2.2.0/24" 
     ] 
    } 
    }, 
    { 
    "name": "pop_b", 
    "subnets": { 
     "Private": [ 
     "192.168.2.0/24,192.168.3.0/24" 
     ], 
     "Public": [ 
     "3.3.3.0/24,4.4.4.0/24" 
     ] 
    } 
    } 
] 
+0

感謝您Coldspeed它爲我工作。你能解釋一下indent = 2是什麼嗎? –

+0

您可以指定用於縮進json的空格數。根級別= 0空格,級別1 = 2空格,級別2 = 4空格,...等等。如果您將縮進更改爲3,則它是0,3,6 ......等等。 –

+0

謝謝,以及如何從new_data打印特定流行音樂......或僅彈出名稱...我無法這麼做... –