Python JSON不从urllib获取数据

时间:2013-01-26 11:38:48

标签: python json urllib2 discogs-api

我正在尝试使用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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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”条目,其中包含许多条目。这些都是“图像”的子条目,“图像”本身没有您可以获取的“uri”属性。

您必须遍历所有图像,与轨道标题相同。将for row in json_object循环替换为:

for row in json_object["images"]:
    print row['uri']
for row in json_object["tracklist"]:
    print row['title']

答案 2 :(得分: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