我试图从我拥有的json文件中仅获取播放列表的名称,但我无法做到
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void)
这是哪里不工作:
{'playlists': [{'description': '',
'lastModifiedDate': '2018-11-20',
'name': 'Piano',
'numberOfFollowers': 0,
'tracks': [{'artistName': 'Kenzie Smith Piano',
'trackName': "You've Got a Friend in Me (From "
'"Toy Story")'},
{'artistName': 'Kenzie Smith Piano',
'trackName': 'A Whole New World (From "Aladdin")'},
{'artistName': 'Kenzie Smith Piano',
'trackName': 'Can You Feel the Love Tonight? (From '
'"The Lion King")'},
{'artistName': 'Kenzie Smith Piano',
'trackName': "He's a Pirate / The Black Pearl "
'(From "Pirates of the Caribbean")'},
{'artistName': 'Kenzie Smith Piano',
'trackName': "You'll be in My Heart (From "
'"Tarzan") [Soft Version]'},
import json
from pprint import pprint
json_data=open('C:/Users/alvar/Desktop/Alvaro/Nueva carpeta/Playlist.json', encoding="utf8").read()
playlist = json.loads(json_data)
pprint(playlist)
我想要的是仅提取播放列表的名称。
答案 0 :(得分:0)
错误是由于您没有访问字典键'playlists'
for plst in playlist['playlists']:
print(plst['name'])
# Piano
答案 1 :(得分:0)
您遍历了错误的对象。
不要忘记json.loads(json_data)
在存储对象时返回该对象。在您的情况下,这是仅包含一个元素的字典:'playlist'
。您必须使用loaded_json['playlist']
访问此元素,然后遍历播放列表列表。
此处,loaded_json
的类型为Dict[List[Dict]]
。注意JSON和嵌套数据结构。
尝试:
loaded_json= json.loads(json_data) #type: Dict[List[dict]]
for playlist in loaded_json['playlist']: #type: dict
print('{}\n'.format(playlist['name']))
这样做,您将获得所有播放列表的名称。