Devs/Python

[Python] json 사용 방법

whawoo 2025. 4. 7. 19:34
반응형

이제는 데이터 전송 등 많은 곳에서 쓰고 있는 json형태이기에 Python에서도 사용방법을 정리해본다

# 파이썬에서 사용하기 위해서 내부 모듈에 있는 json 임포트
import json

new_data = {
	"TestKey": {
		"A": "test",
		"B": "test2"
	}
}

with open("data.json", "w") data_file:
	# json 파일 오픈 후 json 형태로 만든 파일을 json.dump를 사용해서 데이터를 입력
	json.dump(new_data, data_file)
	# 아래처럼 indent를 넣게 되면 위 데이터 형태처럼 들여쓰기가 적용되는 것도 알 수 있다
    	#json.dump(new_data, data_file, indent=4)

#{"TestKey": {"A":"test", "B":"test2"}} 와 같이 json 파일에 저장됨을 알 수 있다

with open("data.json", "r") data_file:
	# json 파일을 열어서 읽어오기
	data = json.load(data_file)
	print(data)

new_data1 = {
	"TestKey1": {
		"A1": "test",
		"B1": "test2"
	}
}

# 데이터 갱신을 하기 위해서 읽어오고 갱신하고 write까지 과정
with open("data.json", "r") data_file:
	# Reading
	data = json.load(data_file)
	# update
	data.update(new_data1)

with open("data.json", "w") data_file:
	# Saving
	json.dump(data, data_file)

 

위와 같이 write의 형태는 dump를 쓰면 되고, Read의 경우 load, update의 경우 update를 호출하면 된다

반응형