랭귀지/python

python json 송수신

유키공 2018. 11. 24. 17:27
json은 URL요청시 입출력 데이터로 많이 활용됩니다. 

예제)

import json
import urllib.request

url = "http://www.test.com"  # URL

d = {'name': '테스트', 'birth': '0703', 'age': 47}
params = json.dumps(d).encode("utf-8")  # encode: 문자열을 바이트로 변환
req = urllib.request.Request(url, data=params,
                             headers={'content-type': 'application/json'})
response = urllib.request.urlopen(req)
print(response.read().decode('utf8'))  # decode: 바이트를 문자열로 변환