Programming/python

파이썬에서 JSON 파일 읽고, 쓰기

방황하는 데이터불도저 2021. 9. 5. 20:11

# JSON (제이슨, JavaScript Object Notation)

 : 속성 - 값 (attribute–value pairs) 또는 키 - 값(key - value pairs) 쌍으로 이루어진다.

  이는 python의 dict 형태와 같다.

 

# JSON의 기본 자료형 (출처 : 위키백과)

 - 수(number) : 정수형 또는 실수형, int or real, 8진수, 16진수 표현 불가

 - 문자열(string) 

 - 참/거짓(true / false) : 소문자

 - 배열(array) : 대괄호 [] 사용

 - 객체(object) : 순서가 없는 이름/값 쌍의 집합으로 이름(키)이 문자열이다. 중괄호 {}사용

 - null : 빈 값

 

 

여러가지 데이터를 다루다보면 json 형태로 되어있는 자료들을 많이 발견할 수 있다.

json파일은 한번도 다뤄본적이 없어 최근 공부를 시작하면서 블로그에 기본적인 코드들을 정리해두려고 한다.

 

# JSON : a built-in package in python 

json 파일을 편리하게 다룰 수 있도록 python에서는 내장모듈로 json package를 지원한다.

 

import json

 

먼저 python에서 json파일을 만들어보자.

 

data = {
	"kpop" : {
		"artist" : "SEVENTEEN",   # str -> string
		"album" : "Your Choice",  # str -> string
		"released" : 20210618,    # int/long/float -> number
		"language" : "Korean",    # str -> string
		"Label" : {"HYBE Labels" : "Pledis Entertainment"},  # dict -> object
		"Writers" : ["Woozi", "Bumzu", "S.Coups", "Mingyu", "danke", "hitman bang", "Kyler Niko"],   # list/tuple -> array
		"Composers" : ["Woozi", "Bumzu", "hitman bang", "WonderKid", "Kyler Niko", "Christoffer Semelius", "H.KENNETH"]   # list/tuple -> array
        # True -> true
        # False -> false
        # None -> null
	}
}

 

# Serialization (Serializing JSON)

python에서 정의한 객체(dict)를 json 파일로 저장하고자 할 때, json.dump(data, write_file) 함수를 사용할 수 있다.

(= 데이터를 일련의 바이트값으로 직렬화(Serialization)시키는 것)

(=JSON파일로 인코딩하는 과정)

with open('example_data.json', 'w') as write_file:
    json.dump(data, write_file)
write_file.close()

 

# Deserialization (Deserializing JSON)

반대로 json 파일을 python객체(dict)로 불러올 때, json.load(read_file) 함수를 사용할 수 있다.

(직렬화된 파일을 다시 객체 형태로 역직렬화(Deserailization)하는 것)

(=JSON파일을 디코딩하는 과정)

with open('example_data.json', 'r') as read_file:
    data = json.load(read_file)
read_file.close()

 

print(type(data['kpop']))
print(type(data['kpop']['artist']))
print(type(data['kpop']['album']))
print(type(data['kpop']['released']))
print(type(data['kpop']['language']))
print(type(data['kpop']['Label']))
print(type(data['kpop']['Writers']))
print(type(data['kpop']['Composers']))

# result
# <class 'dict'>
# <class 'str'>
# <class 'str'>
# <class 'int'>
# <class 'str'>
# <class 'dict'>
# <class 'list'>
# <class 'list'>

 

이외에도 json.dumps, json.loads 함수가 비슷한 역할을 한다.

이는 설명이 너무 길어질 것 같아서 다음에 자세하게 다뤄보도록 하자.