การวนซ้ำผ่านวัตถุ JSON


111

ฉันพยายามวนซ้ำผ่านออบเจ็กต์ 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 :))

คำตอบ:


79

การโหลดข้อมูล 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]:คุณจะทำซ้ำบนปุ่มของคำสั่ง เพราะนั่นคือสิ่งที่คุณจะได้รับเมื่อคุณทำซ้ำตามคำสั่ง หากคุณต้องการที่จะเข้าถึงค่าที่เกี่ยวข้องกับการสำคัญในการ Dict json_object[0][song]ว่าคุณจะใช้ตัวอย่างเช่น

ไม่มีสิ่งนี้เฉพาะสำหรับ JSON เป็นเพียงประเภท Python พื้นฐานโดยมีการใช้งานพื้นฐานตามที่กล่าวไว้ในบทช่วยสอนใด ๆ


ฉันไม่เข้าใจ ฉันพยายามทบทวนสิ่งที่คุณพูดออกไปนอกขอบเขต ฉันค่อนข้างแน่ใจว่าเป็นคำถามเกี่ยวกับ json
myusuf3

7
ไม่ฉันกำลังบอกคุณว่าการทำซ้ำทับคำสั่งจะทำให้คุณได้รับกุญแจ หากคุณต้องการทำซ้ำสิ่งอื่นคุณจะต้องทำซ้ำอย่างอื่น คุณไม่ได้พูดในสิ่งที่คุณต้องการย้ำ บทช่วยสอน Python จะเป็นสถานที่ที่ดีในการค้นหาว่าคุณสามารถทำซ้ำได้อย่างไรและจะทำอะไรได้บ้าง
Thomas Wouters

5
น่าเสียดายที่ยากที่จะอธิบายวิธีการทั้งหมดที่คุณสามารถดึงข้อมูลจากรายการและพจนานุกรมและสตริงในอักขระ 600 ตัวที่คุณสามารถใส่ความคิดเห็นได้ ฉันได้บอกไปแล้วว่าคุณควรจัดทำดัชนีคำสั่งเพื่อรับค่าที่เกี่ยวข้องกับคีย์ ฉันไม่แน่ใจว่าคุณต้องการทบทวนอะไร การเรียนรู้เกี่ยวกับประเภท Python ในตัวเป็นขั้นตอนต่อไป
Thomas Wouters

ไม่มีการทำซ้ำมากนักเมื่อคุณต้องการรับแต่ละรายการ บางทีสิ่งที่คุณต้องการย้ำซ้ำคือjson_objectไม่ใช่json_object[0]จากนั้นรับแต่ละรายการจากแต่ละคำสั่ง
Thomas Wouters

102

ฉันเชื่อว่าคุณอาจหมายถึง:

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

หมายเหตุ: คุณสามารถใช้song.iteritemsแทนsong.itemsif ใน Python 2 ได้


สำหรับแอตทริบิวต์ค่าใน song.iteritems (): เครื่องหมายจุลภาคในบรรทัดนี้หมายถึงอะไร
zakdances

มันเป็นเช่นเดียวกับfor (attribute, value) in song.iteritems():หรือหรือ(var1, var2) = (1, 2) สร้างคู่ (tuples) ค้นหา“ python tuple unpacking” var1, var2 = 1, 2dict.iteritems()(key, value)
tzot

1
สำหรับ python 3 ให้เปลี่ยนsong.iteritemsเป็นsong.items.
Big Pumpkin

44

คำถามนี้มีมานานแล้ว แต่ฉันต้องการให้ข้อมูลว่าโดยปกติฉันจะทำซ้ำผ่านออบเจ็กต์ 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()

2
ไม่มีการห้อยสตริงในโค้ดด้านบน jsonObjectคือdict. for key, value in jsonObject.items():ในโค้ดข้างต้นที่ผมต้องการ
tzot

22

หลังจาก deserializing JSON คุณจะมีวัตถุ python ใช้เมธอดอ็อบเจ็กต์ปกติ

ในกรณีนี้คุณมีรายการพจนานุกรม:

json_object[0].items()

json_object[0]["title"]

เป็นต้น


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

3

สำหรับการทำซ้ำผ่าน JSON คุณสามารถใช้สิ่งนี้:

json_object = json.loads(json_file)
for element in json_object: 
    for value in json_object['Name_OF_YOUR_KEY/ELEMENT']:
        print(json_object['Name_OF_YOUR_KEY/ELEMENT']['INDEX_OF_VALUE']['VALUE'])

2

สำหรับ Python 3 คุณต้องถอดรหัสข้อมูลที่ได้รับกลับมาจากเว็บเซิร์ฟเวอร์ ตัวอย่างเช่นฉันถอดรหัสข้อมูลเป็น 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

หากคุณไม่ถอดรหัสคุณจะได้รับไบต์เทียบกับข้อผิดพลาดสตริงใน Python 3

โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.