使用Python创建Spotify播放列表时如何解决JSON解析错误?
解决Spotify API创建播放列表时的400 JSON解析错误
你遇到的400错误有两个核心原因,对应修改如下:
问题1:请求数据格式错误
你的代码用requests.post的data参数传递字典,但该参数会把数据编码为表单格式(application/x-www-form-urlencoded),而Spotify API明确要求JSON格式的请求体(对应Content-Type: application/json)。
问题2:public字段类型错误
你给public传了字符串'false',但API要求的是布尔值(对应Python里的True/False),字符串类型会导致JSON解析失败。
修改后的代码
把data参数换成json参数,同时修正public的类型:
# To create a playlist playlist_endpoint = f'https://api.spotify.com/v1/users/{my_spotify_id}/playlists' playlist_request_data = { 'name': input('What do you want to call your playlist?').title(), 'description': input('Describe your playlist: '), 'public': False, # 改为布尔值False } playlist_request_headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': f'Bearer {access_code}', } # 把data换成json参数,requests会自动序列化字典为JSON playlist_data = requests.post(url=playlist_endpoint, json=playlist_request_data, headers=playlist_request_headers) print(playlist_data.text)
补充说明
对比官方的curl示例,--data后面是JSON字符串,这和Python中用json参数的效果一致——requests会自动帮你把字典转换成JSON格式的请求体,同时确保Content-Type正确匹配(即使你手动设置了也没问题)。
内容的提问来源于stack exchange,提问作者Philip Igbeka
相关产品推荐
相关产品推荐

