달나라 노트

Python json : json.dumps, json.loads (JSON 데이터 만들기, dictionary를 JSON data로 바꾸기, dictionary를 JSON으로 바꾸기, dictionary JSON 전환, bytes를 dictionary로 바꾸기, JSON data 보기 쉽게 나타내기) 본문

Python/Python Basic

Python json : json.dumps, json.loads (JSON 데이터 만들기, dictionary를 JSON data로 바꾸기, dictionary를 JSON으로 바꾸기, dictionary JSON 전환, bytes를 dictionary로 바꾸기, JSON data 보기 쉽게 나타내기)

CosmosProject 2023. 1. 2. 19:32
728x90
반응형

 

 

 

JSON (JavaScript Object Notation) 데이터는 프로그래밍에서 자주 쓰이는 형태의 데이터입니다.

다양한 정보를 보고 다루기 쉽게 저장할 수 있죠.

 

기본적으로 JSON data는 Python의 dictionary type과 매우 유사합니다.

 

 

Python의 dictionary를 JSON 형태의 string으로 변환하기 위해서는 json library의 dumps method를 사용하면 됩니다.

 

Syntax

json.dumps(dictionary, indent=n)

 

- dictionary

JSON 형태의 string으로 변환할 dictionary 입니다.

 

- indent = n

optional한 parameter입니다.

명시하지 않아도 되며 명시할 경우 출력할 때 더 보기 쉽게 n개 만큼의 공백으로 들여쓰기를 해서 나타내줍니다.

 

 

 

반대로 JSON data나 bytes data를 dictionary로 바꾸려면 json library의 loads method를 사용하면 됩니다.

 

Syntax

json.loads(json)

 

- json

dictionary로 변환할 JSON 또는 bytes type의 데이터입니다.

 

 

 

 

 

 

 

 

 

 

import json

dict_data = {
    "category": "fruits",
    "product_cnt": 2,
    "product": {
        "Apple": {
            "price": 20000,
            "weight": 3
        },
        "Watermelon": {
            "price": 18000,
            "screen_size": 2
        },
    }
}

print(type(dict_data))

json_data = json.dumps(dict_data)
print(json_data)
print(type(json_data))



-- Result
<class 'dict'>

{"category": "fruits", "product_cnt": 2, "product": {"Apple": {"price": 20000, "weight": 3}, "Watermelon": {"price": 18000, "screen_size": 2}}}
<class 'str'>

 

위 코드는 Python dictionary 데이터를 만들고 그것을 JSON type의 string으로 변환하는 코드입니다.

 

- json_data = json.dumps(dict_data)

이 부분이 dictionary를 JSON type string 데이터로 변환하는 부분입니다.

dict_data를 parameter로 주었습니다.

 

변환 후 출력된 내용을 보면 위처럼 data가 출력되며, 출력되는 JSON type string data의 타입은 당연히 문자인 string으로 보입니다.

 

 

근데 위같이 data를 나타내면 한눈에 보기가 쉽지 않죠.

 

아래 코드를 봅시다.

 

import json

dict_data = {
    "category": "fruits",
    "product_cnt": 2,
    "product": {
        "Apple": {
            "price": 20000,
            "weight": 3
        },
        "Watermelon": {
            "price": 18000,
            "screen_size": 2
        },
    }
}

print(type(dict_data))

json_data = json.dumps(dict_data, indent=4)
print(json_data)
print(type(json_data))



-- Result
<class 'dict'>

{
    "category": "fruits",
    "product_cnt": 2,
    "product": {
        "Apple": {
            "price": 20000,
            "weight": 3
        },
        "Watermelon": {
            "price": 18000,
            "screen_size": 2
        }
    }
}
<class 'str'>

 

- json_data = json.dumps(dict_data, indent=4)

이전과 동일하나 indent 옵션을 4로 설정하였습니다.

이 말은 공백 4개를 기본 단위로 하여 들여쓰기를 해서 JSON type string data를 나타내라는 것입니다.

 

그래서 출력된 결과를 보면 줄바꿈과 들여쓰기가 되어 한결 더 보기 편해졌죠.

 

 

 

 

 

 

 

이젠 반대로 JSON type string data를 dictionary로 바꿔보겠습니다.

 

import json

dict_data = {
    "category": "fruits",
    "product_cnt": 2,
    "product": {
        "Apple": {
            "price": 20000,
            "weight": 3
        },
        "Watermelon": {
            "price": 18000,
            "screen_size": 2
        },
    }
}

print(type(dict_data))

json_data = json.dumps(dict_data, indent=4)
print(json_data)
print(type(json_data))

dict_data_new = json.loads(json_data)
print(dict_data_new)
print(type(dict_data_new))



-- Result
<class 'dict'>

{
    "category": "fruits",
    "product_cnt": 2,
    "product": {
        "Apple": {
            "price": 20000,
            "weight": 3
        },
        "Watermelon": {
            "price": 18000,
            "screen_size": 2
        }
    }
}
<class 'str'>

{'category': 'fruits', 'product_cnt': 2, 'product': {'Apple': {'price': 20000, 'weight': 3}, 'Watermelon': {'price': 18000, 'screen_size': 2}}}
<class 'dict'>

 

- dict_data_new = json.loads(json_data)

JSON type string data를 dictionary로 바꾸려면 json library의 loads method를 사용하면 됩니다.

 

마지막에 dict_data_new를 출력한 것을 보면 type이 dictionary로 제대로 변환되었음을 알 수 있습니다.

 

 

 

 

 

 

이번엔 bytes type data를 dictionary로 전환해보겠습니다.

(보통 API등을 이용하면서 GET/POST 방식으로 뭔가를 호출한 후 그 결과를 return받았을 때 json 형태로 구성된 bytes type의 데이터를 전달해주는 경우가 많습니다.)

 

import json

bytes_test = b'{"key1":"first","key2":["element1","element2"]}'
print(type(bytes_test))
print(json.loads(bytes_test))
print(type(json.loads(bytes_test)))



-- Result
<class 'bytes'>
{'key1': 'first', 'key2': ['element1', 'element2']}
<class 'dict'>

 

bytes data도 똑같이 json.loads() method를 통해 dictionary로 바꿀 수 있으며, 위 예시를 보면 bytes type data가 dictionary로 바뀐 걸 알 수 있습니다.

 

 

 

 

 

 

728x90
반응형
Comments