2017-07-04 75 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。