json은 딕셔너리 형식의 외부파일이다.
json에 딕셔너리 형식으로 데이터를 넣고 읽으며 간편하게 저장, 사용이 가능하다.
json 데이터를 추가하는 dump
json 데이터를 읽어오는 load
json 데이터에 새 딕셔너리 json데이터를 추가하는 update
이 세개를 예시와 함께 알아보자.
import json
dict = {
"facebook": {
"email": "werer@gege.com",
"password": "erwqrfefwe"
}
}
try:
with open("a_file.json", "r") as f:
data = json.load(f)
print(data)
except FileNotFoundError:
with open("a_file.json", "w") as f:
json.dump(dict, f, indent=4)
일단 json은 import해야지만 사용할 수 있기 때문에 import해주었다.
그리고 dict이란 딕셔너리에 사이트와 그 사이트의 이메일, 비밀번호 정보를 넣었다.
이제 try: 부분부터 봐보자
with open("a_file.json", "r") as f:
이 코드로 a_file.json이란 이름의 json파일을 가져왔다.
그리고 data = json.load(f) 코드가 있는데,
data란 변수에 f, 즉a_file.json을 읽어와 넣는 코드이다. 그리고 그 데이터를 출력하는 코드를 작성하였다.
그 밑에 except FileNotFoundError:는 만약 파일이 없을 시 실행되는 코드이다.
with open("a_file.json", "w") as f:
파일이 없다면 a_file.json 파일을 생성하고
json.dump(dict, f, intent=4)
a_file.json 파일에 dict 딕셔너리를 추가한다. intent=4는 딕셔너리 문구의 간격인데 문구를 보기 편하게 정리하는 코드라 생각하면 된다. 숫자가 클수록 들여쓰기가 커진다.
- intent 없을 시 저장된 모습
{ "facebook": { "email": "werer@gege.com", "password": "erwqrfefwe" }
- intent 있을 시 저장된 모습
{
"facebook": {
"email": "werer@gege.com",
"password": "erwqrfefwe"
},
이제 위 코드의 실행결과를 봐보자.
a_file.json 파일이 생성되고, 작성했던 dict의 내용이 들어간 것을 볼 수 있다.
여기에 추가로 데이터를 넣고 싶다면 json.update를 사용하면 된다.
데이터를 추가하는 add_data()함수를 작성해보겠다.
import json
dict = {
"facebook": {
"email": "werer@gege.com",
"password": "erwqrfefwe"
}
}
def add_data():
site = input("please write site name: ")
email = input("Please write your email: ")
password = input("Please write your password: ")
new_dict = {
site: {
"email": email,
"password": password
}
}
with open("a_file.json", "r") as f:
data = json.load(f)
data.update(new_dict)
print(data)
with open("a_file.json", "w") as f:
json.dump(data, f, indent=4)
try:
with open("a_file.json", "r") as f:
data = json.load(f)
print(data)
except FileNotFoundError:
with open("a_file.json", "w") as f:
json.dump(dict, f, indent=4)
else:
add_data()
try에서 에러가 일어나지 않는다면, 즉 a_file.json파일이 있다면 add_data()함수가 호출되도록 하였다.
add_data()함수를 보면, 일단 사이트, 이메일, 비밀번호를 유저의 입력을 받아 딕셔너리에 저장하도록 하였다.
with open("a_file.json", "r") as f:
data = json.load(f)
data.update(new_dict)
print(data)
그리고 a_file.json 파일을 읽어와 파일 안의 딕셔너리를 data란 변수에 넣었고,
data.update(new_dict)을 이용하여 data에 new_dict의 내용을 업데이트하여 추가했다.
해당 내용이 제대로 업데이트 되었는지 확인하기 위해 data를 출력했다
with open("a_file.json", "w") as f:
json.dump(data, f, indent=4)
그리고 w모드로 data를 a_file.json에 추가하였다.
- 출력값
{'facebook': {'email': 'werer@gege.com', 'password': 'erwqrfefwe'}}
please write site name: amazon
Please write your email: wejnop@akiehf.net
Please write your password: hfh239jujf
{'facebook': {'email': 'werer@gege.com', 'password': 'erwqrfefwe'}, 'amazon': {'email': 'wejnop@akiehf.net', 'password': 'hfh239jujf'}}
여기서 a모드로 그냥 추가하면 되지 않나? 생각할 수 있지만, 그러면 딕셔너리 구문 형식에 문제가 생겨 에러가 발생한다.
한 번 a모드를 사용하면 어떻게 되는지 확인해보자.
import json
dict = {
"facebook": {
"email": "werer@gege.com",
"password": "erwqrfefwe"
}
}
def add_data():
site = input("please write site name: ")
email = input("Please write your email: ")
password = input("Please write your password: ")
new_dict = {
site: {
"email": email,
"password": password
}
}
with open("a_file.json", "a") as f:
json.dump(new_dict, f, indent=4)
# with open("a_file.json", "r") as f:
# data = json.load(f)
# data.update(new_dict)
# print(data)
#
# with open("a_file.json", "w") as f:
# json.dump(data, f, indent=4)
try:
with open("a_file.json", "r") as f:
data = json.load(f)
print(data)
except FileNotFoundError:
with open("a_file.json", "w") as f:
json.dump(dict, f, indent=4)
else:
add_data()
- 출력값
{'facebook': {'email': 'werer@gege.com', 'password': 'erwqrfefwe'}, 'amazon': {'email': 'wejnop@akiehf.net', 'password': 'hfh239jujf'}}
please write site name: rqwer
Please write your email: giehy879y928h
Please write your password: dsuifgiuqh
이렇게 추가된 데이터 앞에 쉼표가 붙지 않아 파일 구문형식에 에러가 생겨버린다.
때문에 json에 새 딕셔너리 데이터를 추가할 땐 a모드가 아닌 update를 사용하도록 하
'파이썬' 카테고리의 다른 글
파이썬 API 사용 (0) | 2023.08.08 |
---|---|
파이썬으로 메일 발송 (0) | 2023.08.08 |
예외 처리(try, except, else, finally, raise) (0) | 2023.08.04 |
함수 인자 *args, **kwargs (0) | 2023.08.01 |
함수 인자 기본 값 설정 (0) | 2023.08.01 |