[英]How to parse musixmatch python api JSON response?
How do you parse the JSON response from the musixmatch api? 您如何解析musixmatch API的JSON响应? I'm calling the method res = artist_api.artist_search_get(format=format, q_artist=artist) 我正在调用方法res = artist_api.artist_search_get(format = format,q_artist = artist)
I'm getting a response of 我得到了回应
{'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, .........
I'm trying to get the artist_id. 我正在尝试获取artist_id。
I tried getting the artist_id like this: 我试图像这样获得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
I'm getting this error message: 我收到此错误消息:
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__'
Please help I've searched through a bunch of threads but I still can't find the answer to this. 请帮助我搜索了很多线程,但仍然找不到答案。 I'm new to python so I'm not sure what I'm doing wrong. 我是python的新手,所以我不确定自己在做什么错。
You a little messed up with the hierarchy of JSON-document, use this code to get desired values: 您对JSON文档的层次结构有些混乱,请使用以下代码获取所需的值:
[artist['artist']['artist_id'] for artist in res['message']['body']['artist_list']]
As an alternative, can be used JSONPath -expression: $..artist_list..artist_id
to get the same result. 或者,可以使用JSONPath -expression : $..artist_list..artist_id
获得相同的结果。
Example 例
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.