Spotify API:使用 Python 通过 JSON 解析时出错

Posted

技术标签:

【中文标题】Spotify API:使用 Python 通过 JSON 解析时出错【英文标题】:Spotify API: Error parsing through JSON with Python 【发布时间】:2021-12-29 00:00:58 【问题描述】:

在解析从 Spotify 的“用户保存的曲目”端点收到的 JSON 时,我无法将 ID 附加到单独的列表中。

收到的 JSON 如下所示:

    
    "href": "https://api.spotify.com/v1/me/tracks?offset=0&limit=20",
    "items": [
        
            "added_at": "2021-11-16T13:56:51Z",
            "track": 
                "album": 
                    "album_type": "single",
                    "artists": [
                        
                            "external_urls": 
                                "spotify": "https://open.spotify.com/artist/3iKDeO8yaOiWz7vkeljunk"
                            ,
                            "href": "https://api.spotify.com/v1/artists/3iKDeO8yaOiWz7vkeljunk",
                            "id": "3iKDeO8yaOiWz7vkeljunk",
                            "name": "Heavenward",
                            "type": "artist",
                            "uri": "spotify:artist:3iKDeO8yaOiWz7vkeljunk"
                        
                    ],
                    "available_markets": [
                       
                ],
                "disc_number": 1,
                "duration_ms": 224838,
                "explicit": false,
                "external_ids": 
                    "isrc": "QZK6P2040977"
                ,
                "external_urls": 
                    "spotify": "https://open.spotify.com/track/6mJ1nbmQOm6iNClo71K5O6"
                ,
                "href": "https://api.spotify.com/v1/tracks/6mJ1nbmQOm6iNClo71K5O6",
                "id": "6mJ1nbmQOm6iNClo71K5O6",
                "is_local": false,
                "name": "Hole",
                "popularity": 33,
                "preview_url": "https://p.scdn.co/mp3-preview/c425dc91bdb19f1cddf2b35df08e30a03290c3c0?cid=8c9ee97b95854163a250399fda32d350",
                "track_number": 1,
                "type": "track",
                "uri": "spotify:track:6mJ1nbmQOm6iNClo71K5O6"
            
        

现在我用来解析的代码如下所示:

def getLikedTrackIds(session):

    url = 'https://api.spotify.com/v1/me/tracks'
    payload = makeGetRequest(session, url)

    if payload == None:
        return None
    
    liked_tracks_ids = []
    for track in payload['items']:
        for attribute in track['track']:
            if (attribute == 'id'):
                app.logger.info(f"\n\nTrack ID: attribute")
                liked_tracks_ids.append(attribute)
    
    return liked_tracks_ids

对于每首歌曲,我的 like_track_ids 都用字符串“id”填充:

[ "id", "id", "id", "id"....]

谁能提供关于我做错了什么的见解?

【问题讨论】:

作为旁注,我发布的 json 只是我实际收到的一个简短的 sn-p。在我的问题下,还有大约 20 个其他“跟踪”json 对象。 您的代码字面上有if (attribute == 'id'): 后跟liked_tracks_ids.append(attribute) - 这就是您的答案。你可能想要liked_tracks_ids.append(track[attribute]) 或者只是liked_tracks_ids.append(track['id']) @Grismar 是正确的,虽然解决方案是 liked_tracks_ids.append(track['track']['id']) 【参考方案1】:

已在问题下发表评论,但您的代码可以通过摆脱循环来简化:

def getLikedTrackIds(session):

    url = 'https://api.spotify.com/v1/me/tracks'
    payload = makeGetRequest(session, url)

    if payload == None:
        return None
    
    liked_tracks_ids = []
    for track in payload['items']:
        liked_id =  track['track'].get('id', None)
        if liked_id:
            app.logger.info(f"\n\nTrack ID: liked_id")
            liked_tracks_ids.append(liked_id)
    
    return liked_tracks_ids

【讨论】:

以上是关于Spotify API:使用 Python 通过 JSON 解析时出错的主要内容,如果未能解决你的问题,请参考以下文章

使用 Python 的 Spotify API 授权代码流

使用 Spotify API 时“解析 JSON 时出错”

使用 Python 进行 Spotify API 身份验证

在 Spotify 的搜索 API 中按艺术家搜索的正确 python 语法?

多参数 curl 请求 Python、Spotify API

通过 API 在后台使用 spotify 应用程序