遍历JSON对象

160 投票
9 回答
763884 浏览
提问于 2025-04-15 22:08

我正在尝试遍历一个JSON对象来导入数据,比如标题和链接。但是我好像无法获取到冒号(:)后面的内容。

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

这段代码只打印了冒号(:)前的信息。
(忽略贾斯汀·比伯的曲目 :))

9 个回答

62

这个问题已经存在很久了,但我想分享一下我通常是怎么遍历一个JSON对象的。在下面的例子中,我展示了一个写死的字符串,这个字符串里面包含了JSON数据。不过,这个JSON字符串也可以很容易地来自一个网络服务或者一个文件。

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()
162

我觉得你可能是想说:

from __future__ import print_function

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

注意:如果你在用Python 2的话,可以用 song.iteritems 来代替 song.items

113

你加载JSON数据的方式有点脆弱。与其这样:

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

你其实应该这样做:

json_object = json.load(raw)

你不应该把你得到的东西想成是“JSON对象”。你得到的是一个列表。这个列表里包含了两个字典。字典里有各种键值对,都是字符串。当你写 json_object[0] 时,你是在请求列表中的第一个字典。当你用 for song in json_object[0]: 进行循环时,你是在遍历这个字典的键。因为遍历字典时得到的就是它的键。如果你想获取这个字典中某个键对应的值,比如说,你可以用 json_object[0][song]

这些内容并不是JSON特有的。这只是基本的Python类型和它们的基本操作,任何教程里都会讲到。

撰写回答