用Python解析Json嵌套字典(不是列表中的字典)

2024-07-04 08:10:12 发布

您现在位置: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",

希望能够用下面的方法匹配语言的值。我传递的是language('en'),数据是上面的嵌套字典。在

^{pr2}$

该方法可以处理字典列表,但不能处理字典内的词典。。。有谁能告诉我一个地方,在那里我可以学习如何解析嵌套字典?这里我有点迷茫,我找到的所有示例都演示了如何解析到字典列表。在

我得到了:TypeError: string indices must be integers


Tags: 方法json列表data字典artistlanguagelocale
2条回答

我修复了你的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']))

我在python2.7.12上运行了它。在

你可能想试试:除了 像

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

相关问题 更多 >

    热门问题