728x90
1. 인코딩
import json
user = {
"id": "Rachel",
"password": "20230720",
"join": 2023,
"grade": "Gold",
"interests": ["food", "clothes"]
}
# 파이썬 변수를 JSON 객체로 변환하기
json_data = json.dumps(user, indent = 4) # 들여쓰기 네 칸 적용
다음과 같이 JSON 객체로 변환하였다.
{
"id": "Rachel",
"password": "20230720",
"join": 2023,
"grade": "Gold",
"interests": [
"food",
"clothes"
]
}
2. 디코딩
import json
data = json.loads(json_data)
print(data)
3. JSON 파일로 저장하기
import json
# w: 쓰기 모드, with 구문이 끝나면 자동으로 파일을 닫는다.
with open("user.json", "w", encoding="utf-8") as file:
json.dump(user, file, indent = 4)
728x90
'파이썬(Python) 공부' 카테고리의 다른 글
파이썬 sys 모듈에 대해 알아보자 (0) | 2023.08.23 |
---|---|
collections - 컨테이너 데이터형 (0) | 2023.08.18 |
math 라이브러리 (0) | 2023.07.20 |
이진 탐색을 위한 파이썬 bisect 모듈 (0) | 2023.07.20 |
파이썬 순열(Permutations), 조합(Combinations) (0) | 2023.07.20 |