2010-04-28 35 views
50

我想遍歷一個JSON對象來導入數據,即標題和鏈接。我似乎無法獲得超過:的內容。通過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 

此代碼只打印:之前的信息。 (忽略賈斯汀比伯軌道 :))

回答

49

您加載的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類型,其基本操作在任何教程中都有介紹。

+0

我不明白這一點。我試着重複你說的出界。我很確定它的一個問題關於json – myusuf3 2010-04-28 23:41:08

+7

不,我告訴你迭代字典給你的鑰匙。如果你想迭代別的東西,你必須迭代別的東西。你沒有說你想要迭代什麼。 Python教程將是一個很好的地方,可以找出你可以迭代的內容,以及它會做什麼。 – 2010-04-28 23:42:48

+5

不幸的是,要解釋所有可以從600個字符中的列表,字典和字符串中提取數據的方法有點困難,您可以在這些字符中添加註釋。我已經說過,你應該索引字典來獲得與某個密鑰相關的價值。我不確定你想要迭代什麼。瞭解內置的Python類型是下一步。 – 2010-04-28 23:52:06

21

反序列化JSON之後,您將擁有一個python對象。使用常規的對象方法。

在這種情況下,你有一個列表做出詞典:

+0

感謝您的幫助! :) – myusuf3 2010-04-28 23:49:33

8

我會更多的解決這個問題,這樣

import json 
import urllib2 

def last_song(user, limit): 
    # Assembling strings with "foo" + str(bar) + "baz" + ... generally isn't 
    # as nice as using real string formatting. It can seem simpler at first, 
    # but leaves you less happy in the long run. 
    url = 'http://gsuser.com/lastSong/%s/%d/' % (user, limit) 

    # urllib.urlopen is deprecated in favour of urllib2.urlopen 
    site = urllib2.urlopen(url) 

    # The json module has a function load for loading from file-like objects, 
    # like the one you get from `urllib2.urlopen`. You don't need to turn 
    # your data into a string and use loads and you definitely don't need to 
    # use readlines or readline (there is seldom if ever reason to use a 
    # file-like object's readline(s) methods.) 
    songs = json.load(site) 

    # I don't know why "lastSong" stuff returns something like this, but 
    # your json thing was a JSON array of two JSON objects. This will 
    # deserialise as a list of two dicts, with each item representing 
    # each of those two songs. 
    # 
    # Since each of the songs is represented by a dict, it will iterate 
    # over its keys (like any other Python dict). 
    baby, feel_good = songs 

    # Rather than printing in a function, it's usually better to 
    # return the string then let the caller do whatever with it. 
    # You said you wanted to make the output pretty but you didn't 
    # mention *how*, so here's an example of a prettyish representation 
    # from the song information given. 
    return "%(SongName)s by %(ArtistName)s - listen at %(link)s" % baby 
45

json_object[0].items() 

json_object[0]["title"] 

等。我相信你可能是指:

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

屬性,在song.iteritems()中的值:這一行中的逗號意味着什麼? – zakdances 2012-08-09 23:55:34

+0

與song.iteritems():或var(var2)=(1,2)或var1,var2 = 1,2的'(屬性,值)相同。 'dict.iteritems()'產生'(鍵,值)'對(元組)。搜索「python tuple unpacking」。 – tzot 2012-08-11 12:47:53

22

這個問題在這裏已經很長時間了,但我想貢獻一下我通常如何遍歷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() 
+0

字符串索引必須是整數,而不是str – 2016-05-27 21:55:32

1

對於Python 3,您必須解碼從Web服務器返回的數據。比如我對數據進行解碼的UTF8然後用它處理:

# example of json data object group with two values of key id 
jsonstufftest = '{'group':{'id':'2','id':'3'}} 
# always set your headers 
headers = {'User-Agent': 'Moz & Woz'} 
# the url you are trying to load and get json from 
url = 'http://www.cooljson.com/cooljson.json' 
# in python 3 you can build the request using request.Request 
req = urllib.request.Request(url,None,headers) 
# try to connect or fail gracefully 
try: 
    response = urllib.request.urlopen(req) # new python 3 code -jc 
except: 
    exit('could not load page, check connection') 
# read the response and DECODE 
html=response.read().decode('utf8') # new python3 code 
# now convert the decoded string into real JSON 
loadedjson = json.loads(html) 
# print to make sure it worked 
print (loadedjson) # works like a charm 
# iterate through each key value 
for testdata in loadedjson['group']: 
    print (accesscount['id']) # should print 2 then 3 if using test json 

如果不進行解碼你會得到字節串VS錯誤在Python 3