파이썬[Python]: json - dump 함수

파이썬(Phthon): json 모듈 - dump 함수(function)


/// 설명

json 형식과 같이 객체를 직렬화하여 파일 객체에 작성합니다.

obj: 직렬화의 대상입니다.
fp: 파일의 식별자입니다.
skipkeys: False 이면 (str, int, float, bool, None)의 기본 형식을 제외하고는 오류를 발생합니다.
ensure_ascii: True 일 경우 non-ASCII 문자는 escaped 되어집니다. False 일 경우는 그대로 출력됩니다.
check_circular: 순환참조를 점검합니다.(e.g. A=B, B=A)
allow_nan: True 일 경우 (NaN, Infinity, -Infinity) 를 허용합니다.
cls: Json과 관련된 클래스의 하위클래스 생성하여 사용할 경우 사용합니다.
indent: 들여쓰기를 합니다. 숫자와 문자를 허용합니다.
separators: 아이템과, 딕셔너리의 키를 구분합니다. 기본값은 (', ', ': ')입니다.
default: 직렬화되어질 수 없는 것을 가능하게 만들어 주는 함수를 작성하셔야 합니다.
sort_keys: 딕셔너리의 키값으로 정렬하여 출력합니다.

※ 형식
json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

reference
https://docs.python.org/3/library/json.html#module-json

/// 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import json
import sys
import json
# see: ./test_json.txt
test_fd = open('test_json.txt''w')
js = json.dump([12'한글', {'4'5'6': float('NaN')}], test_fd, ensure_ascii=False)
test_fd.close()
js = json.dump([12'한글', {[12]: 5'6': float('NaN')}], skipkeys=True)
print(js)
 
test_json = [21'한글', {'6'5'5': float('NaN')}]
 
# see: ./test_json.txt
test_fd = open('test_json.txt''w')
js = json.dump(test_json, test_fd, ensure_ascii=False)
test_fd.close()
 
js = json.dump(test_json, sys.stdout, ensure_ascii=True)
# [2, 1, "\ud55c\uae00", {"6": 5, "5": NaN}]
 
print()
js = json.dump(test_json, sys.stdout, ensure_ascii=False)
# [2, 1, "한글", {"6": 5, "5": NaN}]
 
print()
js = json.dump(test_json, sys.stdout, allow_nan=True)
# [2, 1, "\ud55c\uae00", {"6": 5, "5": NaN}]
 
print()
js = json.dump(test_json, sys.stdout, separators=(','':'))
# [2,1,"\ud55c\uae00",{"6":5,"5":NaN}]
 
print()
js = json.dump(test_json, sys.stdout, sort_keys=True)
# [2, 1, "\ud55c\uae00", {"5": NaN, "6": 5}]
 
print()
js = json.dump(test_json, sys.stdout, indent='____')
# [
# ____2,
# ____1,
# ____"\ud55c\uae00",
# ____{
# ________"6": 5,
# ________"5": NaN
# ____}
# ]
 
cs

* 실행환경: Microsoft Windows 10 Homes
* 인터프리터: 파이썬(Python 3.9)


– 당신을 응원합니다. –

댓글

이 블로그의 인기 게시물

파이썬[Python]: 내장함수 - from_bytes 메서드

파이썬[Python]: 내장함수 - __len__ 메서드

파이썬[Python]: kivy - 한글 사용

파이썬[Python]: 내장함수 - bit_length 메서드

C 언어: sin 함수, cos 함수, tan 함수