2015-11-01 5 views
5

Mam folder, w którym mam około 20000 plików synów. Chcę poznać wszystkie unikalne klucze każdego json i chcę wziąć zjednoczenie wszystkich kluczy. Ale ja utknąłem tylko w pierwszym kroku. Mogę znaleźć klucze do pliku z jednym synem.print Wszystkie klucze pliku json w pytonie

I napisał następujący kod do tej pory:

from pprint import pprint 
import json 
json_data=open("/Users/akira/out/1.json") 
jdata = json.load(json_data) 

for key, value in jdata: 
    pprint("Key:") 
    pprint(key) 

To daje mi błąd w następujący sposób:

Traceback (most recent call last): 
File "/Users/akira/PycharmProjects/csci572/linkedbased.py",  line 8, in <module> 
    for key, value in jdata: 
ValueError: need more than 1 value to unpack 

Moje json jest zagnieżdżona json.Please zasugerować mi jak mogę dostać wszystkie klucze.

{ 
"a": "Offer", 
"inLanguage": "et", 
"availabl": { 
    "a": "Place", 
    "address": { 
     "a": "PostalAddress", 
     "name": "Oklahoma" 
    } 
}, 
"description": "Smith and Wesson 686 357 magnum 6 inch barrel wood handle great condition shoots great.", 
"priceCurrency": "USD", 
"geonames_address": [ 
    { 
     "a": "PopulatedPlace", 
     "hasIdentifier": { 
      "a": "Identifier", 
      "label": "4552707", 
      "hasType": "http://dig.isi.edu/gazetteer/data/SKOS/IdentifierTypes/GeonamesId" 
     }, 
     "hasPreferredName": { 
      "a": "Name", 
      "label": "Tahlequah" 
     }, 
     "uri": "http://dig.isi.edu/gazetteer/data/geonames/place/4552707", 
     "fallsWithinState1stDiv": { 
      "a": "State1stDiv", 
      "uri": "http://dig.isi.edu/gazetteer/data/geonames/place/State1stDiv/US_OK", 
      "hasName": { 
       "a": "Name", 
       "label": "Oklahoma" 
      } 
     }, 
     "score": 0.5, 
     "fallsWithinCountry": { 
      "a": "Country", 
      "uri": "http://dig.isi.edu/gazetteer/data/geonames/place/Country/US", 
      "hasName": { 
       "a": "Name", 
       "label": "United States" 
      } 
     }, 
     "fallsWithinCountyProvince2ndDiv": { 
      "a": "CountyProvince2ndDiv", 
      "uri": "http://dig.isi.edu/gazetteer/data/geonames/place/CountyProvince2ndDiv/US_OK_021" 
     }, 
     "geo": { 
      "lat": 35.91537, 
      "lon": -94.96996 
     } 
    } 
], 
"price": 750, 
"title": "For Sale: Smith &amp; Wesson 686", 
"publisher": { 
    "a": "Organization", 
    "name": "armslist.com", 
    "uri": "http://dig.isi.edu/weapons/data/organization/armslist" 
}, 
"uri": "http://dig.isi.edu/weapons/data/page/13AD9516F01012C5F89E8AADAE5D7E1E2BA97FF9/1433463841000/processed", 
"seller": { 
    "a": "PersonOrOrganization", 
    "description": "Private Party" 
} //, ... 
} 

Odpowiedz

7

Zamiast for key, value in jdata: użyć for key, value in jdata.items(): takiego:

for key, value in data.items(): 
    pprint("Key:") 
    pprint(key) 

Spójrz na docs dla dict:

egzemplarze():

zwróci nowy widok elementów słownika ((klucz, wartość) par).

EDIT: Jeśli chcesz uzyskać wszystkie zagnieżdżone klucze, a nie tylko z najlepszymi z nich poziomie, można przyjąć podejście jak te zaproponowane w another answer tak:

def get_keys(dl, keys_list): 
    if isinstance(dl, dict): 
     keys_list += dl.keys() 
     map(lambda x: get_keys(x, keys_list), dl.values()) 
    elif isinstance(dl, list): 
     map(lambda x: get_keys(x, keys_list), dl) 

keys = [] 
get_keys(jdata, keys) 

print(keys) 
# [u'a', u'inLanguage', u'description', u'priceCurrency', u'geonames_address', u'price', u'title', u'availabl', u'uri', u'seller', u'publisher', u'a', u'hasIdentifier', u'hasPreferredName', u'uri', u'fallsWithinState1stDiv', u'score', u'fallsWithinCountry', u'fallsWithinCountyProvince2ndDiv', u'geo', u'a', u'hasType', u'label', u'a', u'label', u'a', u'uri', u'hasName', u'a', u'label', u'a', u'uri', u'hasName', u'a', u'label', u'a', u'uri', u'lat', u'lon', u'a', u'address', u'a', u'name', u'a', u'description', u'a', u'name', usury'] 

print(list(set(keys))) # unique list of keys 
# [u'inLanguage', u'fallsWithinState1stDiv', u'label', u'hasName', u'title', u'hasPreferredName', u'lon', u'seller', u'score', u'description', u'price', u'address', u'lat', u'fallsWithinCountyProvince2ndDiv', u'geo', u'a', u'publisher', u'hasIdentifier', u'name', u'priceCurrency', u'geonames_address', u'hasType', u'availabl', u'uri', u'fallsWithinCountry'] 
1

powinieneś użyć dict.items() lub dict.iteritems() w for key, value in jdata

So, powinna ona być

for key, value in jdata.items(): 

LUB

for key, value in jdata.iteritems(): 

Patrz odpowiedź na to pytanie, aby znać różnicę między tymi dwoma: What is the difference between dict.items() and dict.iteritems()?

Jeśli tylko trzeba iteracyjne nad klucze słownika, można nawet spróbować dict.keys() lub dict.iterkeys()

+0

Po prostu chciałem dodać notatkę, że '.iteritems()' zostało usunięte w Pythonie 3. –

+1

oh! czasy się zmieniają! Powinienem dowiedzieć się więcej o Pythonie 2 i Pythonie 3 – Vipul