파이썬/파이썬(python) 중급

[30-5 파이썬] JSON, json.dump(), json.load(), json.update(), 제이슨

Olivia-BlackCherry 2022. 9. 19. 19:36

JSON 제이슨

JavaScript Object Notation

 

 

제이슨의 장점

제이슨은 원래 자바스크립트에서

'데이터 전송'을 위한 방법으로 설계되었지만

단순하고 이해하기 쉬운 구조

파이썬 외 다른 언어에서도 자주 사용되고 있다.

 

특히 인터넷에서 데이터를 전송할 때 자주 사용하는데,

제이슨을 이용하면 아주 쉽게 데이터를 로딩하고,

원하는 정보를 빠르게 검색할 수 있다.

 

 

 

Json data ------ Python Dictionary

상호호환성

제이슨 데이터의 구조가 딕셔너리이기 때문에

제이슨의 메소드인 json.load(), json.dump()를 이용하여

제이슨데이터를을 파이썬데이터로,

파이썬데이터를 제이슨데이터로 

언제든지 바꿀 수 있다.

 

 

 

제이슨 구조

제이슨의 구조를 살펴보면,

딕셔너리 구조와 매우 비슷하다. 

데이터는 키:쌍의 구조를 가지고 있고,

nested list와 여러 dictionary들로 구성되어 있다.

{
    "naver": {
        "email": "olivia@coding.co.kr",
        "password": "sdfdfsdafsd"
    },
    "instagram": {
        "email": "olivia-ins@coding.co.kr",
        "password": "asdfsfsfasf"
    },
}

 

 

제이슨 라이브러리

파이썬 내장모듈이기 때문에 따로 설치할 필요는 없다. 

제이슨을 write 쓰고, Read 읽고, update 갱신할 때는 

아래의 메소드를 사용한다.

Write Read Update
json.dump() json.load() 기존데이터.update(새로운 데이터)

 

 

 

제이슨 파일 생성하기

1) 기본 환경 설정하기

json을 import 한다.

website, email, password  세 가지 데이터를 변수에 입력받는다.

import json

website = input("웹사이트?")
email = input("e-mail?")
password = input("password?")

 

 

2) 저장할 데이터 만들기

제이슨의 데이터구조는 딕셔너리이다. 

키와 값을 쌍으로 한 데이터를 만들어야 한다.

data = {
    website:{
        "e-mail: ": email,
        "password: ": password
    }

}

 

 

3) 데이터를 제이슨 파일로 저장하기

 

V 쓰기: json.dump()

데이터를 새로운 제이슨 파일에 write 한다. 

dump() 메소드를 쓴다. 

파라미터는

데이터이름  data

파일경로 file

이다.

with open("data.json", "w") as file:
    json.dump(data, file)

저장된 모습

파일명: data.json

{"Naver": {"e-mail: ": "olivia@naver.com", "password: ": "olivia"}}

 

데이터 간격 띄워 저장하기

데이터를 저장할 때, 

파라미터로 'indent=숫자'를 추가하여

들여쓰기를 할 공백을 숫자만큼 주어서

사람이 코드를 읽기 쉽도록 배려할 수도 있다.

파라미터는

indent = 숫자 : indent =4

{
    " Instagram": {
        "e-mail: ": " olivia-coding@face.book.co.kr",
        "password: ": "sdkfjl"
    }
}

 

 

V 읽기 :  json.load()

data.json파일을 read 한다.

load() 메소드를 쓴다. 

파라미터는

파일경로 file 

이다.

with open("data.json", "r") as file:
    json_data = json.load(file)
    print(json_data)

>>

{' Instagram': {'e-mail: ': ' olivia-coding@face.book.co.kr', 'password: ': 'sdkfjl'}}

 

 

 

V 업데이트: 기존 데이터.update(새로운 데이터)

기본적으로 json.update는 다음의 형식을 띈다.

기존 데이터.update(새로운 데이터)

 

json 파일의 내용을 update 하는 방법은 다소 복잡하니 천천히 따라해보도록 하자.

1. 데이터를 로드한다.

with open("data.json", "r") as file:
    json_data = json.load(file)

 

2. 데이터를 업데이트한다.

with open("data.json", "r") as file:
    json_data = json.load(file)
    new_data = json_data.update(data)

 

3. 데이터를 저장한다.

with open("data.json", "w") as file:
    json.dump(json_data, file, indent=4)

 

<최종코드>

import json

website = input("웹사이트?")
email = input("e-mail?")
password = input("password?")

data = {
    website:{
        "e-mail: ": email,
        "password: ": password
    }

}
with open("data.json", "r") as file:
    json_data = json.load(file)
    json_data.update(data)

with open("data.json", "w") as file:
    json.dump(json_data, file, indent=4)

 

 

<유의할 것>

만일,  위와 같이 하지 않고 update만 했을 경우 아래의 문제점이 발생한다.

 

with open("data.json", "r") as file:
    json_data = json.load(file)
    json_data.update(data)
    print(json_data)

>>(instagram, google) 두 개의 데이터가 출력된다.

{' Instagram': {'e-mail: ': ' olivia-coding@face.book.co.kr', 'password: ': 'sdkfjl'}, 

'google': {'e-mail: ': 'olivia@google.com', 'password: ': 'aldksf'}}

 

 

그런데 

실제 "data.json" 파일의 내용이 변하지 않는다는 것을 알 수 있다.

data.json 파일(google 데이터는 추가되지 않았다)

{
    " Instagram": {
        "e-mail: ": " olivia-coding@face.book.co.kr",
        "password: ": "sdkfjl"
    }
}

 

따라서

마지막에 dump() 메소드로 데이터를 새롭게 쓰고 저장해야한다는 것을 잊지 말자!