JSON Encoding, Decoding 에 대한 포스팅 입니다.
json 모듈의 load()
또는 loads()
함수를 사용합니다.
load()
함수 : JSON 파일을 읽어 dict 객체로 변환loads()
함수 : JSON 문자열을 읽어 dict 객체로 변환devices.json : json 예시 파일 입니다.
{
"devices": [
{
"name": "Galaxy Note 9",
"width": 414,
"height": 846,
"pixelRatio": 3.5,
"userAgent": "Mozilla/5.0 (Linux; Android 10; SAMSUNG SM-N960N) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/13.0 Chrome/83.0.4103.106 Mobile Safari/537.36"
},
{
"name": "iPhone X/XS",
"width": 375,
"height": 812,
"pixelRatio": 3,
"userAgent": "Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/12.0 Mobile/15A372 Safari/604.1"
},
{
"name": "Samsung Galaxy Tab 3(10.1-inch)",
"width": 800,
"height": 1280,
"pixelRatio": 1,
"userAgent" : "Mozilla/5.0 (Linux; Android 7.1.2; GT-P5210) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.81 Safari/537.36"
},
{
"name": "iPad Pro(12.9-inch)",
"width": 1024,
"height": 1366,
"pixelRatio": 2,
"userAgent": "Mozilla/5.0 (iPad; CPU OS 11_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.0 Mobile/15E148 Safari/604.1"
}
]
}
devices.json 파일로부터 각 필드 값을 읽는 파이썬 코드 입니다.
아래 예시는 JSON 파일을 읽으므로 load()
함수를 사용하였습니다.
import json
def read_json_file():
with open('devices.json') as jf:
json_data = json.load(jf)
devices = json_data["devices"]
for device in devices:
name = device["name"]
width = device["width"]
height = device["height"]
dpi = device["pixelRatio"]
ua = device["userAgent"]
print(name, width, height, dpi, ua)
실행 결과는 아래와 같습니다.
Galaxy Note 9 414 846 3.5 Mozilla/5.0 (Linux; Android 10; SAMSUNG SM-N960N) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/13.0 Chrome/83.0.4103.106 Mobile Safari/537.36
iPhone X/XS 375 812 3 Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/12.0 Mobile/15A372 Safari/604.1
Samsung Galaxy Tab 3(10.1-inch) 800 1280 1 Mozilla/5.0 (Linux; Android 7.1.2; GT-P5210) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.81 Safari/537.36
iPad Pro(12.9-inch) 1024 1366 2 Mozilla/5.0 (iPad; CPU OS 11_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.0 Mobile/15E148 Safari/604.1
requests 모듈의 json()
함수를 사용하여 문자열을 dict 객체로 변환합니다.
예시 API 주소는 https://koreanjson.com/comments 입니다.
위 API 주소로부터 200개의 댓글 내용을 가져와서 출력하는 파이썬 코드 입니다.
import requests
from requests import HTTPError
def read_api_json():
url = "https://koreanjson.com/comments"
try:
response = requests.get(url)
response.raise_for_status()
json_data = response.json()
for i in range(0, 200):
comment = json_data[i]['content']
print(comment)
except HTTPError:
print("HTTP Error")
실행 결과는 아래와 같습니다. (예시 API 주소에서 제공하는 댓글 내용이 대한민국헌법 내용인가 봅니다.)
간혹 데이터가 JSON이 아니라 JSONP(JSON with Padding)로 내려오는 경우가 있습니다. 이런 경우에는 JSONP 문자열을 JSON 형태로 파싱한 이후에 문자열->dict 객체로 변환해줘야 합니다.
import json
def read_jsonp():
jsonp_data_example = 'callback({"message": "You got an AJAX response via JSONP from another site!"});'
string_data = jsonp_data_example[jsonp_data_example.index('(') + 1: jsonp_data_example.rindex(')')] # JSONP -> JSON 형태로 파싱
json_data = json.loads(string_data) # STR -> DICT 변환
print(json_data['message'])
위 코드 실행 시, JSON 데이터로 정상 변환되어 "message" 내용만 출력되는 걸 확인할 수 있습니다.
You got an AJAX response via JSONP from another site!
json 모듈의 dump()
또는 dumps()
함수를 사용합니다.
dumps()
함수 : dict 객체를 직렬화된 JSON 문자열로 변환 dump()
함수 : dict 객체를 스트림 객체(파일 등)로 변환dumps()
import json
def write_json_string():
json_data = {
"devices": [
{
"name": "Samsung Galaxy Tab 3(10.1-inch)",
"width": 800,
"height": 1280,
"pixelRatio": 1,
"userAgent": "Mozilla/5.0 (Linux; Android 7.1.2; GT-P5210) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.81 Safari/537.36"
},
{
"name": "iPad Pro(12.9-inch)",
"width": 1024,
"height": 1366,
"pixelRatio": 2,
"userAgent": "Mozilla/5.0 (iPad; CPU OS 11_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.0 Mobile/15E148 Safari/604.1"
}
]
}
string_data = json.dumps(json_data)
print(string_data)
위 코드 실행 시, 아래와 같이 한줄의 json 문자열로 변환되어 출력됩니다.
{"devices": [{"name": "Samsung Galaxy Tab 3(10.1-inch)", "width": 800, "height": 1280, "pixelRatio": 1, "userAgent": "Mozilla/5.0 (Linux; Android 7.1.2; GT-P5210) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.81 Safari/537.36"}, {"name": "iPad Pro(12.9-inch)", "width": 1024, "height": 1366, "pixelRatio": 2, "userAgent": "Mozilla/5.0 (iPad; CPU OS 11_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.0 Mobile/15E148 Safari/604.1"}]}
dump()
import json
def write_json_file():
json_data = {
"name": "Sangyeon Song",
"email": "sangyeon217@gmail.com"
}
with open(file='info.json', mode='w') as f:
json.dump(json_data, f)
위 코드 실행 시, 아래와 같이 JSON 데이터를 담은 info.json 파일이 생성됩니다.
{"name": "Sangyeon Song", "email": "sangyeon217@gmail.com"}