如何解析 musixmatch python api JSON 响应?

How to parse musixmatch python api JSON response?

如何解析来自 musixmatch api 的 JSON 响应? 我正在调用方法 res = artist_api.artist_search_get(格式=格式,q_artist=艺术家)

我收到的回复是

{'message': {'body': {'artist_list': [{'artist': {'artist_alias_list': [],
                                                  'artist_comment': '',
                                                  'artist_country': '',
                                                  'artist_credits': {'artist_list': []},
                                                  'artist_edit_url': None,
                                                  'artist_id': 26575484.0,
                                                  'artist_mbid': None,
                                                  'artist_name': 'Illenium',
                                                  'artist_name_translation_list': [],
                                                  'artist_rating': 55.0, .........

我正在尝试获取 artist_id。

我试过这样得到 artist_id:

    print(res['message']['body']['artist']['artist_id'])
artist_api = swagger_client.ArtistApi()
format = 'json' 

try:
    artist_list = ["adele", "lady gaga", "john legend"];
    for artist in artist_list:
        print(artist)
        res = artist_api.artist_search_get(format=format, q_artist=artist)
        print(res['message']['body']['artist']['artist_id'])
except ApiException as e:
    print "Exception when calling ArtistApi->artist_search_get: %s\n" % e

我收到此错误消息:

Traceback (most recent call last):
  File "musixmatch.py", line 39, in <module>
    print(res['message']['body']['artist_id'])
TypeError: 'InlineResponse2004' object has no attribute '__getitem__'

请帮助我已经搜索了一堆线程,但我仍然找不到这个问题的答案。我是 python 的新手,所以我不确定自己做错了什么。

你有点搞砸了 JSON-文档的层次结构,使用此代码获取所需的值:

[artist['artist']['artist_id'] for artist in res['message']['body']['artist_list']]

作为替代,可以使用 JSONPath-expression: $..artist_list..artist_id 来获得相同的结果。

例子

from jsonpath_rw import parse
import json

res = json.loads("""{
  "message": {
    "header": {},
    "body": {
      "artist_list": [
        {
          "artist": {
            "artist_credits": {            },
            "artist_country": "string",
            "artist_id": 110
          }
        },
        {
          "artist": {
            "artist_credits": {},
            "artist_country": "string",
            "artist_id": 220
          }
        }        
      ]
    }
  }
}""")

# 1-way: Iterate through JSON-document
print([artist['artist']['artist_id'] for artist in res['message']['body']['artist_list']])
# result: [110, 220]

# 2-way: Use JSONPath-expression
jsonpath_expr = parse('$..artist_list..artist_id')
print([match.value for match in jsonpath_expr.find(res)])
# result: [110, 220]