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 트랙 무시 :))
JSON 데이터로드는 약간 취약합니다. 대신에:
json_raw= raw.readlines()
json_object = json.loads(json_raw[0])
당신은 정말로해야합니다 :
json_object = json.load(raw)
You shouldn't think of what you get as a "JSON object". What you have is a list. The list contains two dicts. The dicts contain various key/value pairs, all strings. When you do json_object[0]
, you're asking for the first dict in the list. When you iterate over that, with for song in json_object[0]:
, you iterate over the keys of the dict. Because that's what you get when you iterate over the dict. If you want to access the value associated with the key in that dict, you would use, for example, json_object[0][song]
.
None of this is specific to JSON. It's just basic Python types, with their basic operations as covered in any tutorial.
I believe you probably meant:
for song in json_object:
# now song is a dictionary
for attribute, value in song.iteritems():
print attribute, value # example usage
NB: use song.items
instead of song.iteritems
for Python 3.
This question has been out here a long time, but I wanted to contribute how I usually iterate through a JSON object. In the example below, I've shown a hard-coded string that contains the JSON, but the JSON string could just as easily have come from a web service or a file.
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()
After deserializing the JSON, you have a python object. Use the regular object methods.
In this case you have a list made of dictionaries:
json_object[0].items()
json_object[0]["title"]
etc.
I would solve this problem more like this
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
For Python 3, you have to decode the data you get back from the web server. For instance I decode the data as utf8 then deal with it:
# 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
If you don't decode you will get bytes vs string errors in Python 3.
for iterating through JSON you can use this:
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'])
참고URL : https://stackoverflow.com/questions/2733813/iterating-through-a-json-object
'IT story' 카테고리의 다른 글
ggplot2에서 그리드, 배경색, 상단 및 오른쪽 테두리 제거 (0) | 2020.09.04 |
---|---|
파이썬 : TO, CC 및 BCC로 메일을 보내는 방법은 무엇입니까? (0) | 2020.09.04 |
파이썬 pylab 플롯 정규 분포 (0) | 2020.09.04 |
ActiveRecord 모델에서 getter 메서드를 어떻게 덮어 쓸 수 있습니까? (0) | 2020.09.04 |
테이블 행에 테두리 반경을 추가하는 방법 (0) | 2020.09.04 |