[Python] dictionary를 JSON으로 변환
반응형
Python에서는 json module의 json.dumps() Method를 사용하여 dictionary를 JSON 문자열로 변환합니다.
import json my_dict = {'a': 1, 'b': 2, 'c': 3} json_string = json.dumps(my_dict) print(json_string)
Output :
'{"a": 1, "b": 2, "c": 3}'
json.dump() Method를 사용하여 JSON 문자열을 파일로 저장할 수 있습니다.
with open("data.json", "w") as f: json.dump(my_dict, f)
json.dumps() 메서드에는 추가 파라미터를 지정할 수 있습니다. indent, separators, sort_keys 등이 있습니다.
indent 파라미터는 JSON 문자열을 일반적으로 읽기 쉽게 포맷팅 하는데 사용되고, separators 파라미터는 key-value 사이의 구분자를 지정하는데 사용됩니다. sort_keys 파라미터는 JSON 문자열에서 key를 정렬하는데 사용됩니다.
Decimal, date, time, datetime, timedelta, UUID 등과 같은 특정 타입은 기본적으로 직렬화되지 않습니다. 이러한 타입을 처리하려면 사용자 정의 JSONEncoder를 사용해야 합니다.
반응형
'Tech & Development > Programming Languages' 카테고리의 다른 글
[Python] File 개수 확인 (0) | 2023.01.18 |
---|---|
[Python] 문자열 줄바꿈 하는 방법 (0) | 2023.01.17 |
[Python] *args와 **kwargs 사용방법 (0) | 2022.11.21 |
[Python] dictionary(딕셔너리) Value로 Key찾기 (0) | 2022.06.10 |
[Python] 문자열에서 숫자만 추출하기 (0) | 2022.03.30 |
댓글
이 글 공유하기
다른 글
-
[Python] File 개수 확인
[Python] File 개수 확인
2023.01.18 -
[Python] 문자열 줄바꿈 하는 방법
[Python] 문자열 줄바꿈 하는 방법
2023.01.17Python에서는 개행 문자 \n을 사용하여 문자열에 줄 바꿈을 추가할 수 있습니다. 예를 들면 다음과 같습니다. string = "This is the first line.\nThis is the second line." print(string) Output: This is the first line. This is the second line. 문자열 클래스의 join() 메서드를 사용하여 여러 문자열을 줄바꿈으로 합칠 수도 있습니다. 예를 들면 다음과 같습니다. lines = ["This is the first line.", "This is the second line."] string = "\n".join(lines) print(string) 이렇게 하면 위의 Output과 동일하게 출력됩니다. … -
[Python] *args와 **kwargs 사용방법
[Python] *args와 **kwargs 사용방법
2022.11.21 -
[Python] dictionary(딕셔너리) Value로 Key찾기
[Python] dictionary(딕셔너리) Value로 Key찾기
2022.06.10Python에서 dictionary(딕셔너리) 타입은 immutable한 키(key)와 mutable한 값(value)으로 맵핑되어 있는 순서가 없는 집합입니다. 일반적인 딕셔너리 타입은 중괄호로 되어 있고 키와 값으로 이루어져 있습니다. test_dict = {'0': 'AA', '1': 'BB', '2': 'CC', '3': 'DD'} test_dict >> {'0': 'AA', '1': 'BB', '2': 'CC', '3': 'DD'} key를 이용하여 value를 찾는 방법은 다음과 같습니다. test_dict.get('3') >> 'CC' test_dict['3'] >> 'CC' 반대로 value를 이용해 key를 찾는 방법은 다음과 같습니다. [k for k, v in test_dict.ite…
댓글을 사용할 수 없습니다.