python - API 调用中的 JSON 结果

标签 python json

如果我使用 last.fm API,使用 pylast 包装器,并查找类似轨道,如下所示:

track = last.get_track('Radiohead', 'Karma Police')
    for similar in track.get_similar():
        print (similar)

我得到:

SimilarItem(item=pylast.Track(u'Radiohead', u'No Surprises', pylast.LastFMNetwork('key', 'secret', 'string', 'user', 'string2')), match=1.0)
SimilarItem(item=pylast.Track(u'Radiohead', u'Paranoid Android', pylast.LastFMNetwork('key', 'secret', 'string', 'user', 'string2')), match=0.995)

如果我尝试对其进行索引:

track = last.get_track('Radiohead', 'Karma Police')
    for similar in track.get_similar():
        print (similar[0])

我得到:

Radiohead - No Surprises
Radiohead - Paranoid Android

我想以这种方式打印类似:

         {
         "artist": "Radiohead",
         "track":"No surprises"
         },
         {
         "artist": "Radiohead",
         "track":"No surprises"
        }

但是如果我尝试类似[0][0],我会收到以下错误:

类型错误:“Track”对象不支持索引

那么如何将结果构造为字典

最佳答案

如果你想要一本字典,你可以这样做:

track = last.get_track('Radiohead', 'Karma Police')
d = dict(str(item[0]).split(" - ") for item in track.get_similar())

关于python - API 调用中的 JSON 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40167211/

相关文章:

java - 从 json 响应中解析一个值,其中大部分负载都是冗余的

python - python 字符串实际上在硬件级别上是不可变的吗?

python - 将纪元时间截断为小时/天的开始

python - BeautifulSoup 不处理 anchor 标记内的 HTML 表格

javascript - 在 Javascript 中使用索引键值 JSON 创建新数组

android - 对于 int 值,JSON 响应始终返回零

html - 如何在 Angular 2 模板中获取 json 对象的长度

python - 如何检查两个字符串是否在python中有交集?

python - 迭代到python中的第n个值

javascript - 如何在发送到 AngularJS 中的服务器之前从 JSON 中删除多余的引号