遍历JSON对象

2024-03-29 07:14:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图遍历一个JSON对象来导入数据,即title和link。我似乎找不到超过:的内容。

JSON:

[
    {
        "title": "Baby (Feat. Ludacris) - Justin Bieber",
        "description": "Baby (Feat. Ludacris) by Justin Bieber on Grooveshark",
        "link": "http://listen.grooveshark.com/s/Baby+Feat+Ludacris+/2Bqvdq",
        "pubDate": "Wed, 28 Apr 2010 02:37:53 -0400",
        "pubTime": 1272436673,
        "TinyLink": "http://tinysong.com/d3wI",
        "SongID": "24447862",
        "SongName": "Baby (Feat. Ludacris)",
        "ArtistID": "1118876",
        "ArtistName": "Justin Bieber",
        "AlbumID": "4104002",
        "AlbumName": "My World (Part II);\nhttp://tinysong.com/gQsw",
        "LongLink": "11578982",
        "GroovesharkLink": "11578982",
        "Link": "http://tinysong.com/d3wI"
    },
    {
        "title": "Feel Good Inc - Gorillaz",
        "description": "Feel Good Inc by Gorillaz on Grooveshark",
        "link": "http://listen.grooveshark.com/s/Feel+Good+Inc/1UksmI",
        "pubDate": "Wed, 28 Apr 2010 02:25:30 -0400",
        "pubTime": 1272435930
    }
]

我试着用字典:

def getLastSong(user,limit):
    base_url = 'http://gsuser.com/lastSong/'
    user_url = base_url + str(user) + '/' + str(limit) + "/"
    raw = urllib.urlopen(user_url)
    json_raw= raw.readlines()
    json_object = json.loads(json_raw[0])

    #filtering and making it look good.
    gsongs = []
    print json_object
    for song in json_object[0]:   
        print song

此代码只打印:之前的信息。 (忽略Justin Bieber曲目)


Tags: comjsonhttpurlrawtitlelinkbaby
3条回答

JSON数据的加载有点脆弱。而不是:

json_raw= raw.readlines()
json_object = json.loads(json_raw[0])

你真的应该这样做:

json_object = json.load(raw)

你不应该把你得到的看作是一个“JSON对象”。你只有一张单子。这个列表包含两条指令。dict包含各种键/值对,所有字符串。当你做json_object[0]时,你要求的是列表中的第一个dict。当您使用for song in json_object[0]:迭代dict的键时,您将迭代dict的键。因为这是您在迭代dict时得到的结果。如果您想要访问与dict中的键相关联的值,您将使用例如json_object[0][song]

这些都不是JSON特有的。这只是基本的Python类型,它们的基本操作在任何教程中都有介绍。

这个问题在这里已经提出了很长时间,但我想贡献我通常如何遍历JSON对象。在下面的示例中,我展示了一个包含JSON的硬编码字符串,但是JSON字符串也可以很容易地来自web服务或文件。

import json

def main():

    # create a simple JSON array
    jsonString = '{"key1":"value1","key2":"value2","key3":"value3"}'

    # change the JSON string into a JSON object
    jsonObject = json.loads(jsonString)

    # print the keys and values
    for key in jsonObject:
        value = jsonObject[key]
        print("The key and value are ({}) = ({})".format(key, value))

    pass

if __name__ == '__main__':
    main()

我相信你的意思是:

for song in json_object:
    # now song is a dictionary
    for attribute, value in song.iteritems():
        print attribute, value # example usage

注意:对于Python 3,使用song.items而不是song.iteritems

相关问题 更多 >