Итерация через объект 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

Этот код только печатает информацию прежде :. (проигнорируйте дорожку Justin Bieber :))

91
задан fragilewindows 22 November 2016 в 14:38
поделиться

4 ответа

Загрузка данных JSON немного нестабильна. Вместо:

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

вы действительно должны просто сделать:

json_object = json.load(raw)

Вы не должны думать о том, что вы получаете, как о «объекте JSON». У вас есть список. В списке два словаря. В словарях содержатся различные пары ключ / значение, все строки. Когда вы выполняете json_object [0] , вы запрашиваете первый диктант в списке. Когда вы повторяете это, используя для песни в json_object [0]: , вы перебираете ключи словаря. Потому что это то, что вы получаете, когда повторяете dict. Если вы хотите получить доступ к значению, связанному с ключом в этом dict, вы должны использовать, например, json_object [0] [song] .

Все это не относится к JSON.Это просто базовые типы Python, с их основными операциями, описанными в любом учебнике.

71
ответ дан 24 November 2019 в 06:43
поделиться

Я бы решил эту проблему примерно так

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
8
ответ дан 24 November 2019 в 06:43
поделиться

После десериализации JSON у вас есть объект python. Используйте обычные методы объекта.

В этом случае у вас есть список словарей:

json_object[0].items()

json_object[0]["title"]

и т. Д.

20
ответ дан 24 November 2019 в 06:43
поделиться

Думаю, вы имели в виду:

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

NB: используйте song.items вместо song.iteritems для Python 3.

87
ответ дан 24 November 2019 в 06:43
поделиться
Другие вопросы по тегам:

Похожие вопросы: