상세 컨텐츠

본문 제목

Handling JSON files

Coding/잡동사니

by linguana 2021. 6. 24. 10:32

본문

json (JavaScript Object Notation)

json 파일을 읽고 쓰는 법에 대해서 알아보도록 하자.


[1]에 대한 내용

예를 들어 아래와 같은 student.json 파일이 있다.

{ 
    "student0":{ 
        "firstName":"John",
        "lastName":"Smith",
        "age":35,
        "city":"New York"
    },
    "student1":{ 
        "firstName":"Mary",
        "lastName":"Brown",
        "age":27,
        "city":"Los Angeles"
    },
    "student2":{ 
        "firstName":"Lily",
        "lastName":"Green",
        "age":45,
        "city":"Austin"
    }
}

보기 어려우니까 표로 정리해보면:

학생 firstName lastName age city
student0 John Smith 35 New York
student1 Mary Brown 27 Los Angeles
student2 Lily Green 45 Austin

 

1. json 및 pandas 라이브러리로 읽는 법.

import json
import pandas as pd

# use the built-in json module
with open('students.json') as json_file:
    students0 = json.load(json_file)

# use the pandas module
with open('students.json') as json_file:
    students1 = pd.read_json(json_file, orient='index')

print(students0)
print(students1)

프린트 결과:

{'student0': {'firstName': 'John', 'lastName': 'Smith', 'age': 35, 'city': 'New York'}, 
'student1': {'firstName': 'Mary', 'lastName': 'Brown', 'age': 27, 'city': 'Los Angeles'}, 
'student2': {'firstName': 'Lily', 'lastName': 'Green', 'age': 45, 'city': 'Austin'}}

          age         city firstName lastName
student0   35     New York      John    Smith
student1   27  Los Angeles      Mary    Brown
student2   45       Austin      Lily    Green

 

2. json 파일 쓰는 법

import json
import pandas as pd

# use the built-in json module
teacher = {'name': 'Mike', 'age': 50}
with open('teacher.json', 'w+') as file:
    json.dump(teacher, file)

# use the pandas module
activities = [['Mon', 'Basketball'], ['Wed', 'Soccer'], ['Sun', 'Karate']]
df = pd.DataFrame(activities, columns=['Day', 'Activity'])
with open('activities.json', 'w+') as file:
    df.to_json(file, orient='index')

표로 시각화해보자:

(1) teacher.json

name age
Mike 50

 

(2) activities.json

Day Activities
Mon Basketball
Wed Soccer
Sun Karate

 

파일 쓴 결과:

### The following is the teacher.json data; This line is not the data.
{
    "name":"Mike",
    "age":50
}

### The following is the activities.json data; This line is not the data.
{
    "0":{
        "Day":"Mon",
        "Activity":"Basketball"
    },
    "1":{
        "Day":"Wed",
        "Activity":"Soccer"
    },
    "2":{
        "Day":"Sun",
        "Activity":"Karate"
    }
}

Object Detection을 위한 json 파일 deserialization [2]

1. Encoding (python → json)

1.1. 메소드 .dumps()는 파이썬 dict 자료형을 json string 자료형으로 변환하는데 쓰인다.

json.dumps example

 

1.2. i/o operation (입출력)이랑 dump() 메소드를 활용해서 json 파일 쓰는 법도 있음
(json 파일을 "w" 모드로 쓴다)

json.dump example

 

2. Decoding (json → python)

2.1. json.loads() 혹은 json.load() 메소드로 디코딩 가능.
(디코딩이란 구체적으로 json 객체가 python dict 자료형이 되는 것임)

json.loads example

dict 객체가 되서 .get() 메소드를 사용할 수 있구나.

2.2. i/o operation

open으로 json 파일을 연다. json.load() 메소드를 활용함.

open operation으로 json 파일 열었음

3. 인자 indent=4 sort_keys=True 활용하기

pretty print

indent=4로 이쁘게 인코딩하기

 

4. Serialization 그리고 Deserialization

4.1. JSONEncoder (python → json)

JSONEncoder.encode()

4.2. JSONDecoder (json → python)

JSONDecoder().decode()

 

입출력 연산과 빈 dict 자료형 활용법

import json
#File I/O Open function for read data from JSON File
data = {} #Define Empty Dictionary Object

try:
        with open('json_file_name.json') as file_object:
                data = json.load(file_object)
                
except ValueError:
     print("Bad JSON file format,  Change JSON File")

Extra

Python CSV to JSON - Python Examples

csv 파일을 json 파일로 변환하는 걸 파이썬 프로그램으로 어떻게 하는지 보여줌. Related articles에서 보면 json 파일을 가지고 할 수 있는 여러 가지를 알려줘서 유용함.


References

[1] Handle JSON Data Using JSON and Pandas in Python | by Yong Cui | The Startup | Medium
[2] Python JSON: Encode(dumps), Decode(loads) & Read JSON File (guru99.com)    
[3] R, Python 분석과 프로그래밍의 친구 (by R Friend) :: [Python] Python으로 JSON 데이터 읽고 쓰기 (Read and Write JSON data by Python) (tistory.com)

'Coding > 잡동사니' 카테고리의 다른 글

Generator basics (yield)  (0) 2021.07.01
python zip function  (0) 2021.06.29
Jupyter Notebook Tutorial  (0) 2021.06.23
Deep Learning AI Course 4  (0) 2021.06.23
Linux commands  (0) 2021.06.22

관련글 더보기