I have a problem with the deserialization of a json file using only the requests library and I have not found anything that can help me. The json file has multiple types with the same name and my intent is to have the contents only of the first block.
This is the code of the function I use:
def toId(nome):
api = "https://api.deezer.com/search/track?q=" + nome
bas1 = requests.get(api)
for element in bas1.json():
tit = element['title_short']
return tit
I would like to get the title of the song in the first block(title: "Diego Armando Maradona") but I can't get it because there are more then 1 element with the type "title"; I also get the error (TypeError: string indices must be integers ).
How can i proceed? Thanks for the help
I would like to get the title of the song in the first block
Firstly, the list of songs is in the object keyed by data
, then you need to select the right one:
Translate that to code:
songs = bas1.json()['data']
return songs[0]['title_short']
You probably want to check that you've got any though, so:
songs = bas1.json()['data']
return songs[0]['title_short'] if songs else None
In your current code, you'd hit an error if there were no songs in the list (ie the returned data was []
), because tit
would be unassigned on the return
line.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.