본문 바로가기
Python

[Python] Json 형태의 데이터 다루기

by teamnova 2023. 6. 13.

파이썬을 이용해 Json 형태의 데이터를 처리하기 위해 사용되는 내장 모듈인 json 을 사용해서 json 파일을 생성하고 조회, 수정 하는 예제를 작성해 보겠습니다. 

 

loads() 함수: JSON 문자열을 Python 객체로 변환

JSON 문자열을 Python의 객체로 변환하기 위해서는 loads() 함수를 사용합니다.

 

import json

data = {
    "Teamnova1" : {
        "gender": "female",
        "age" : 30,
        "hobby" : ["reading", "music"]
    },
    "Teamnova2" : {
        "gender": "male",
        "age" : 18,
        "hobby" : ["development", "painting"]
    }
}

file_path = "./test.json"

with open(file_path, 'w', encoding='utf-8') as file:
    json.dump(data, file)
    #json 모듈의 dump() 를 사용하여 dictionary 형태의 데이터를 json 파일로 저장

 

작성된 Json 파일

json 파일로 저장할 때 indentation(들여쓰기)을 주고싶으시다면,

with open(file_path, 'w', encoding='utf-8') as file:
    json.dump(data, file, indent="\t")

json.dump() 를 사용하실 때 indent Parameter에 원하는 값을 입력하시면 됩니다.

1, 2 와 같은 숫자를 입력하셔서 해당 숫자만큼의 스페이스 크기로 들여쓰기를 하셔도 되고,

예시와 같이 "\t", 즉 탭으로 들여쓰기를 하셔도 됩니다.

 

들여쓰기 된 Json 파일 모습

Json 파일 읽기 - json.load()

import json

file_path = "./test.json"

with open(file_path, 'r') as file:
    data = json.load(file)
    print(type(data))
    print(data)
    print(data["Teamnova1"])
    #json 모듈의 load() 를 json 파일을 읽어와 dictionary 형태로 사용하실 수 있음.

파이썬에서 json.load() 를 이용해 json 파일을 읽어오면 dictionary 형태로 데이터를 활용할 수 있습니다. 

결과값

JSON 파일 수정

import json

file_path = "./test.json"

# 기존 json 파일 읽어오기
with open(file_path, 'r') as file:
    data = json.load(file)

# 데이터 수정
data["Teamnova1"]["age"] = 26
data["Teamnova1"]["hobby"].append("take a picture")
data["Teamnova2"]["age"] = 29
data["Teamnova2"]["hobby"].append("travel")

# 기존 json 파일 덮어쓰기
with open(file_path, 'w', encoding='utf-8') as file:
    json.dump(data, file, indent="\t")

데이터가 수정된 것을 확인할 수 있습니다.