0

我正在尝试使用 discogs API 获取 JSON 数据,但是当我将数据作为原始数据粘贴到浏览器中时,代码似乎没有给出我看到的输出。请让我知道我在这里做错了什么,因为我是 Python 新手。我正在寻找标题,图像的输出。谢谢!

Python:

import urllib
import urllib2
import json
url = 'http://api.discogs.com/masters/66271'
request = urllib2.Request('http://api.discogs.com/masters/66271')
request.add_header('User-Agent','Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
request.add_header('Content-Type','application/json')
response = urllib2.urlopen(request)
json_raw= response.readlines()
json_object = json.loads(json_raw[0])
print json_object
for row in json_object:
    print row
            print row['title']

错误的输出:

styles
genres
videos
title
main_release
main_release_url
uri
artists
versions_url
year
images
resource_url
tracklist
id
data_quality
4

3 回答 3

1

你不应该使用.readlines(). 让json图书馆阅读:

response = urllib2.urlopen(request)
json_object = json.load(response)

注意函数名,.load(),最后没有s

返回的对象是一个字典;您看到的每个字符串都是该字典的键。您需要指定您想要的标题;和条目都有一个带有标题的项目列表tracklistvideos这是您打印tracklist条目标题的方式:

for track in json_object['tracklist']:
    print track['title']

哪个打印:

HIStory Begins
Billie Jean
The Way You Make Me Feel
Black Or White
Rock With You
She's Out Of My Life
Bad
I Just Can't Stop Loving You
Man In The Mirror
Thriller
Beat It
The Girl Is Mine
Remember The Time
Don't Stop 'Til You Get Enough
Wanna Be Startin' Somethin'
Heal The World
HIStory Continues
Scream
They Don't Care About Us
Stranger In Moscow
This Time Around
Earth Song
D.S.
Money
Come Together
You Are Not Alone
Childhood (Theme From "Free Willy 2")
Tabloid Junkie
2 Bad
History
Little Susie
Smile
于 2013-01-26T11:46:05.570 回答
1

您从 JSON 获得的数组如下所示:

{
    u 'images': [{
        u 'uri': u 'http://api.discogs.com/image/R-446273-1356211752-6937.jpeg',
    }, {
        u 'uri': u 'http://api.discogs.com/image/R-446273-1239130419.jpeg',
    }, {
        u 'uri': u 'http://api.discogs.com/image/R-446273-1239130427.jpeg',
    }, {
    ...
}

有一个“图像”条目,其中包含许多条目。这些都是“images”的子条目,“images”本身没有可以获取的“uri”属性。

您必须遍历所有图像,与曲目标题相同。用这个替换你的for row in json_object循环:

for row in json_object["images"]:
    print row['uri']
for row in json_object["tracklist"]:
    print row['title']
于 2013-01-26T11:50:16.960 回答
1

试试这个,

opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11')]
http_handle = opener.open(url)
jsonContent = http_handle.read()
http_handle.close()

import json
data = json.load(jsonContent)
data["videos"]["title"]//will return the title
data["videos"]["images"]["uri"]//will return the image url
于 2013-01-26T11:55:04.943 回答