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 트랙을 무시합니다 :)
당신의 뜻은 아마도 다음과 같습니다.
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
NB: 다음을 사용할 수 있습니다.song.iteritems대신에song.itemsPython 2에서.
당신이 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 유형이며 기본적인 작업은 모든 튜토리얼에서 다룹니다.
이 질문은 오래전부터 있었지만, 저는 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()
JSON을 역직렬화한 후에 파이썬 객체가 생성됩니다.일반 개체 메서드를 사용합니다.
이 경우 사전으로 구성된 목록이 있습니다.
json_object[0].items()
json_object[0]["title"]
기타.
저는 이 문제를 더 이렇게 해결할 것입니다.
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
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'])
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
디코딩하지 않으면 파이썬 3에서 바이트 대 문자열 오류가 발생합니다.
다른 솔루션 추가(Python 3) - 디렉터리 및 각 파일에서 json 파일을 통해 모든 개체를 반복하고 관련 필드를 인쇄합니다.
코드에서 주석을 참조하십시오.
import os,json
data_path = '/path/to/your/json/files'
# 1. Iterate over directory
directory = os.fsencode(data_path)
for file in os.listdir(directory):
filename = os.fsdecode(file)
# 2. Take only json files
if filename.endswith(".json"):
file_full_path=data_path+filename
# 3. Open json file
with open(file_full_path, encoding='utf-8', errors='ignore') as json_data:
data_in_file = json.load(json_data, strict=False)
# 4. Iterate over objects and print relevant fields
for json_object in data_in_file:
print("ttl: %s, desc: %s" % (json_object['title'],json_object['description']) )
json 문자열을 변수에 저장할 수 있는 경우jsn_string
import json
jsn_list = json.loads(json.dumps(jsn_string))
for lis in jsn_list:
for key,val in lis.items():
print(key, val)
출력:
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);
http://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
언급URL : https://stackoverflow.com/questions/2733813/iterating-through-a-json-object
'programing' 카테고리의 다른 글
| 도커 내에서 MariaDB를 실행할 수 없습니다. (0) | 2023.07.22 |
|---|---|
| Oracle SQL Developer 3.1.07 listagg를 사용한 문자 사이의 추가 공백 (0) | 2023.07.22 |
| 문자열 형식 지정 시 동일한 값을 여러 번 삽입 (0) | 2023.07.22 |
| Linux에서는 strrev() 기능을 사용할 수 없습니까? (0) | 2023.07.22 |
| '따옴표가 붙은 문자열이 제대로 종료되지 않음'을(를) 유발하는 SQL에서 단일 따옴표를 이스케이프하는 방법은 무엇입니까? (0) | 2023.07.22 |