如何解析musixmatch python api JSON响应?

时间:2019-08-03 19:00:12

标签: python json api musixmatch

您如何解析musixmatch api的JSON响应? 我在叫方法 res = artist_api.artist_search_get(format = format,q_artist = 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的新手,所以我不确定自己做错了什么。

1 个答案:

答案 0 :(得分:0)

您对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]