2017-07-04 76 views
0

我有這些可怕的嵌套JSON字典與Python解析JSON的嵌套字典(內部沒有列出字典)

"data": { 
      "assetID": "VMSA0000000000310652", 
      "lastModified": "2017-06-02T19:36:36.535-04:00", 
      "locale": { 
       "MetadataAlbum": { 
       "Artists": { 
        "Artist": { 
        "ArtistName": "Various Artists", 
        "ArtistRole": "MainArtist" 
        } 
       }, 
       "Publishable": "true", 
       "genres": { 
        "genre": { 
        "extraInfos": null, 
        } 
       }, 
       "lastModified": "2017-06-02T19:32:46.296-04:00", 
       "locale": { 
        "country": "UK", 
        "language": "en", 

並希望能夠匹配與下面的方法將外語的重要性。我傳遞語言('en'),數據是上面的嵌套字典。

def get_localized_metadataalbum(language, data): 
    for locale in data['locale']: 
     if data['locale'].get('MetadataAlbum') is not None: 
      if data['locale'].get('MetadataAlbum').get('locale') is not None: 
       if data['locale'].get('MetadataAlbum').get('locale').get('language') is not None: 
        if data['locale'].get('MetadataAlbum').get('locale').get('language') == language: 
         return data['locale'] 

return None 

該方法適用於字典的列表,而不是裏面的字典詞典...任何人都可以點我在哪裏可以學習如何通過嵌套的字典解析的地方嗎?我在這裏有點迷路,我發現的所有例子都展示瞭如何解析字典列表。

我已經得到:TypeError: string indices must be integers

+0

請關閉您的正確字典結構。 –

+0

你能澄清一下,如果你有時會通過字典,有時會列出?然後您必須檢查數據的類型(例如,鍵入(mydata)== dict)。對於循環在詞典中檢查此https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops。 –

回答

0

你可能想嘗試:除了 像

try: 
    assert x in data.keys() for x in ["x","y"] 
    ... 
    return data["x"]["y"] 
except: 
    return None 
0

我定你的JSON。我放入字符串並正確關閉括號。這按預期工作:

import json 

json_string = """ 
    {"data": { 
      "assetID": "VMSA0000000000310652", 
      "lastModified": "2017-06-02T19:36:36.535-04:00", 
      "locale": { 
       "MetadataAlbum": { 
       "Artists": { 
        "Artist": { 
        "ArtistName": "Various Artists", 
        "ArtistRole": "MainArtist" 
        } 
       }, 
       "Publishable": "true", 
       "genres": { 
        "genre": { 
        "extraInfos": null 
        } 
       }, 
       "lastModified": "2017-06-02T19:32:46.296-04:00", 
       "locale": { 
        "country": "UK", 
        "language": "en" 
       } 
       } 
      } 
     } 
    } 
    """ 

json_data = json.loads(json_string) 

print(json_data) 


def get_localized_metadataalbum(language, data): 
    for locale in data['locale']: 
     if data['locale'].get('MetadataAlbum') is not None: 
      if data['locale'].get('MetadataAlbum').get('locale') is not None: 
       if data['locale'].get('MetadataAlbum').get('locale').get('language') is not None: 
        if data['locale'].get('MetadataAlbum').get('locale').get('language') == language: 
         return data['locale'] 

    return None 

print('RESULT:') 
print(get_localized_metadataalbum("en", json_data['data'])) 

我跑它在python 2.7.12。