프로그래밍 언어/Python
Python - json 형식
Flashback
2021. 9. 16. 10:27
728x90
반응형
0. 준비단계
pip install json
pip3 install json
파이썬 버전에 맞게 json라이브러리를 설치해준다.
1. import 선언
import json # json라이브러리를 가져온다.
2. json 문자열로 변환 - dumps()
json.dumps() : Python의 객체를 JSON 문자열로 변환
def get_json():
json_result = {}
json_result['test1'] = "python1"
json_result['test2'] = "python2"
json_result['test3'] = "python3"
return json_result
print(get_json())
json.dumps를 사용하지 않으면 파이썬 객체로 만들어 출력시킨다.
def get_json():
json_result = {}
json_result['test1'] = "python1"
json_result['test2'] = "python2"
json_result['test3'] = "python3"
return json.dumps(json_result)
print(get_json())
json.dumps로 파이썬의 객체가 아니라 JSON으로 변환된 것을 확인할 수 있다.
3. json -> python객체 - loads()
json.loads() : JSON 형식을 Python의 객체 타입으로 변환
import json
def get_json():
json_result = {}
json_result['test1'] = "python1"
json_result['test2'] = "python2"
json_result['test3'] = "python3"
return json.dumps(json_result)
print(json.loads(get_json()))
json.loads로 json타입의 객체를 파이썬의 객체타입인 dict로 변환시킬 수 있다.
728x90
반응형