我想检查json响应中是否存在密钥,但是当前正在标题中显示错误;
这是我的代码;
for i in range(len(MoviesLoadedData)):
URL_1080p = ""
if MoviesLoadedData[i]['torrents']['en']['1080p'] in MoviesLoadedData[i]['torrents']['en']:
URL_1080p = MoviesLoadedData[i]['torrents']['en']['1080p']['url']
else:
pass
这里是json响应;
{
"_id": "tt1408101",
"imdb_id": "tt1408101",
"title": "Star Trek Into Darkness",
"torrents": {
"en": {
"1080p": {
"url": "magnet:?xt=urn:btih:BF5529C12559DB47FEA3E57BC7ECE827D188589B&tr=udp://glotorrents.pw:6969/announce&tr=udp://tracker.opentrackr.org:1337/announce&tr=udp://torrent.gresille.org:80/announce&tr=udp://tracker.openbittorrent.com:80&tr=udp://tracker.coppersurfer.tk:6969&tr=udp://tracker.leechers-paradise.org:6969&tr=udp://p4p.arenabg.ch:1337&tr=udp://tracker.internetwarriors.net:1337",
"seed": 803,
"peer": 169,
"size": 2093796557,
"filesize": "1.95 GB",
"provider": "YTS"
},
"720p": {
"url": "magnet:?xt=urn:btih:A73CEF306766938EA033DD373FD30337696A8E39&tr=udp://glotorrents.pw:6969/announce&tr=udp://tracker.opentrackr.org:1337/announce&tr=udp://torrent.gresille.org:80/announce&tr=udp://tracker.openbittorrent.com:80&tr=udp://tracker.coppersurfer.tk:6969&tr=udp://tracker.leechers-paradise.org:6969&tr=udp://p4p.arenabg.ch:1337&tr=udp://tracker.internetwarriors.net:1337",
"seed": 428,
"peer": 90,
"size": 967615447,
"filesize": "922.79 MB",
"provider": "YTS"
}
}
}
}
任何帮助/建议将不胜感激。
答案 0 :(得分:0)
如果您想检查'1080p'
是否是字典中的键
MoviesLoadedData[i]['torrents']['en']
,
那么你想要:
if '1080p' in MoviesLoadedData[i]['torrents']['en']:
您要检查的是dict是否
MoviesLoadedData[i]['torrents']['en']['1080p']
是键,这是不可能的,因为字典不能是哈希键。
答案 1 :(得分:0)
这应该做到:
if MoviesLoadedData[i]['torrents']['en']['1080p']:
url_1080p = MoviesLoadedData[i]['torrents']['en']['1080p']['url']
print(url_1080p)