오답노트
[Python3] JSON 패키지 본문
JSON
서버에서 클라이언트로 데이터를 보낼 때 사용하는 양식 중 하나이다.
파이썬 JSON 패키지
json — JSON 인코더와 디코더 — Python 3.10.5 문서
json — JSON 인코더와 디코더 소스 코드: Lib/json/__init__.py JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 4627) and by ECMA-404, is a lightweight data interchange format inspired by JavaScript object literal syn
docs.python.org
파이썬에서 json 패키지를 추가하면 사용할 수 있다.
별도에 설치는 필요없이 import 시키면 된다.
json 패키지 함수
함수에 관해서 자세한 옵션은 위 항목을 참고하자.
아래는 기본적으로 다루는 방법만 설명한다.
dumps
딕셔너리 변수를 json 양식으로 바꿔주는 함수다.
json 양식으로 바뀌면 자료형은 str이 된다.
함수 인자로 ensure_ascii = False 를 넣으면 한글을 사용할 수 있다.
indent = '\t'를 사용하면 더 보기좋은 json 형태로 만들어준다.
import json
# 딕셔너리 변수
data = {
"Person" : {
"name" : "박대기", "age" : 30
}
}
# 딕셔너리 -> json
json_data = json.dumps(data, ensure_ascii=False,indent='\t')
print(json_data)
dump
딕셔너리 변수를 json 파일로 만들어준다.
옵션 설명은 dumps와 같다.
import json
from collections import OrderedDict
# 딕셔너리 변수
data = {
"Person" : {
"name" : "박대기", "age" : 30
}
}
json_data2 = OrderedDict()
json_data2 = data
#딕셔너리 -> json 파일
with open("../Python_file_json/sample.json", 'w') as f:
json.dump(data,f,ensure_ascii=False, indent = '\t')
load
json 파일을 딕셔너리로 만들어준다.
import json
#json 파일 -> 딕셔너리
with open("../Python_file_json/sample.json", 'r') as f:
json_read_data = json.load(f)
print("\n읽기1(",type(json_read_data),") : ")
print(json_read_data)
print(json_read_data["Person"]["name"])
loads
문자열을 json 형태로 변환한다.
import json
#json 파일 -> str
with open("../Python_file_json/sample.json", 'r') as f:
json_read_data2 = f.read()
json.loads(json_read_data2)
print("\n읽기2(",type(json_read_data2),") : ")
print(json_read_data2)
GitHub - dhjkl123/Python_file_json: file and json handling by Python
file and json handling by Python. Contribute to dhjkl123/Python_file_json development by creating an account on GitHub.
github.com
'Python' 카테고리의 다른 글
[Colab] 런타임 중지 방지 (0) | 2022.10.23 |
---|---|
[Python] iterator / yield (0) | 2022.08.06 |
[Python3] 파일 읽기/쓰기 (0) | 2022.07.06 |
[Python3] 문자열 (0) | 2022.07.05 |
[Python3] 클래스(Class) (0) | 2022.07.03 |