반응형
문자열을 dict로 변환하여 반복 할 수있는 방법이 있습니까? 아니면 그대로 (str 유형) 파싱해야합니까?
from urllib.request import urlopen
url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'
response = urlopen(url)
print(response.read()) # returns string with info
해결 방법
response.read ()
를 인쇄했을 때 b
가 문자열 앞에 붙는 것을 발견했습니다 (예 : b '{ "a": 1, .. ). "b"는 바이트를 의미하며 처리중인 객체 유형에 대한 선언 역할을합니다.
json.loads ( 'string')
를 사용하여 문자열을 dict로 변환 할 수 있다는 것을 알고 있었기 때문에 바이트 유형을 문자열 유형으로 변환해야했습니다. utf-8 decode ( 'utf-8')
에 대한 응답을 디코딩하여이를 수행했습니다. 문자열 유형이되면 문제가 해결되었고 dict
를 쉽게 반복 할 수있었습니다.
이것이 이것을 작성하는 가장 빠른 또는 가장 '비단뱀적인'방법인지는 모르겠지만 작동하며 항상 최적화 및 개선 시간이 있습니다! 내 솔루션에 대한 전체 코드 :
from urllib.request import urlopen
import json
# Get the dataset
url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'
response = urlopen(url)
# Convert bytes to string type and string type to dict
string = response.read().decode('utf-8')
json_obj = json.loads(string)
print(json_obj['source_name']) # prints the string with 'source_name' key
참조 페이지 https://stackoverflow.com/questions/23049767
반응형
'파이썬' 카테고리의 다른 글
파이썬 Creating a zero-filled pandas data frame (0)
2020.12.15
파이썬 How to read a file in reverse order? (0)
2020.12.15
파이썬 Get date and time when photo was taken from EXIF data using PIL (0)
2020.12.15
파이썬 Postgres 테이블에 DataFrame을 작성하는 방법은 무엇입니까? (0)
2020.12.15
파이썬으로 BDD 연습하기 (0)
2020.12.15
댓글