Developer/Python
Python JSON을 Dictionary로, Dictionary를 JSON으로 변환 방법 (json to dict / dict to json)
roqkfrlfhr
2022. 1. 2. 13:36
Python JSON을 Dictionary로, Dictionary를 JSON으로 변환 방법 (json to dict / dict to json)
Python 에서 HTTP 통신 등으로 데이터를 주고 받을 때 JSON 형태로 주고 받는 경우가 많이 있습니다.
이럴 때 JSON을 Python에서 원활하게 사용할 수 있도록
JSON을 Dictionary 형태로로 변환하는 방법, Dictionary 형태를 JSON 으로 변환하는 방법을 알아야 합니다.
Python에서 json을 dictionary로, dictionary를 json으로 변환하는 방법을 알려드리도록 하겠습니다.
Python에 존재하는 json 모듈을 사용하면 간단하게 변환하실 수 있습니다.
JSON to Dictionary - json.loads()
import json
json_example = '{"olivia": {"gender": "female", "age": 25, "hobby": ["reading", "music"]}, "Tyler": {"gender": "male", "age": 28, "hobby": ["development", "painting"]}}'
dict_example = json.loads(json_example) # Convert json to dict
print("JSON Type : ", type(json_example))
print("JSON : ", json_example)
print("Dictionary Type : ", type(dict_example))
print("Dictionary : ", dict_example)
# Output
# JSON Type : <class 'str'>
# JSON : {"olivia": {"gender": "female", "age": 25, "hobby": ["reading", "music"]}, "Tyler": {"gender": "male", "age": 28, "hobby": ["development", "painting"]}}
# Dictionary Type : <class 'dict'>
# Dictionary : {'olivia': {'gender': 'female', 'age': 25, 'hobby': ['reading', 'music']}, 'Tyler': {'gender': 'male', 'age': 28, 'hobby': ['development', 'painting']}}
json 모듈의 loads()를 사용하여 JSON을 Dictionary 로 간단하게 변환할 수 있습니다.
Dictionary to JSON - json.dumps()
import json
dict_example = {
"olivia" : {
"gender": "female",
"age" : 25,
"hobby" : ["reading", "music"]
},
"Tyler" : {
"gender": "male",
"age" : 28,
"hobby" : ["development", "painting"]
}
}
json_example = json.dumps(dict_example) # Convert dict to json
print("Dictionary Type : ", type(dict_example))
print("Dictionary : ", dict_example)
print("JSON Type : ", type(json_example))
print("JSON : ", json_example)
# Output
# Dictionary Type : <class 'dict'>
# Dictionary : {'olivia': {'gender': 'female', 'age': 25, 'hobby': ['reading', 'music']}, 'Tyler': {'gender': 'male', 'age': 28, 'hobby': ['development', 'painting']}}
# JSON Type : <class 'str'>
# JSON : {"olivia": {"gender": "female", "age": 25, "hobby": ["reading", "music"]}, "Tyler": {"gender": "male", "age": 28, "hobby": ["development", "painting"]}}
json 모듈의 dumps()를 사용하여 Dictionary 를 JSON으로 간단하게 변환할 수 있습니다.
이상으로 Python에서 json을 dictionary로, dictionary를 json으로 변환하는 방법에대한 설명을 마치도록 하겠습니다.
도움이 되셨다면 공감, 댓글 부탁드립니다!
궁금하신 점이나 요청사항은 언제든지 말씀해주세요!
피드백도 언제나 환영입니다!
감사합니다.