본문 바로가기

코딩/파이썬 표준 라이브러리

[Python][json] JSON 파일 읽기

 

JSON (JavaScript Object Notation)에 대한 정보는 json.org에서 확인이 가능하다.

 

JSON 파일의 기본 구조는 아래의 object와 array로 구성되며,

  • '{'와 '}'로 구성되는 object
  • '['와 ']'로 구성되는 array

JSON 파일의 구성 요소와 파이썬 데이터 타입 간의 관계는 아래와 같다.

 

JSON Python
object dict
array list
string str
number (int 또는 float) int 또는 float
true True
false False

 

읽을 JSON 파일이 다음과 같은 경우,

 

{
    "object": "dict",
    "array": "list",
    "string": "str",
    "number": [
        {
            "int": 1
        },
        {
            "float": 1.23
        }
    ],
    "true": true,
    "false": false
}

 

JSON 파일의 주요 구성 요소의 데이터 타입을 확인하는 코드를 작성하고 실행하니,

 

import json

print()

with open('samp_json.json', 'r') as jf:
    jcont = json.load(jf)
    print('jcont type = ', type(jcont))

print('jcont len = ', len(jcont), '\n')

for k, v in jcont.items():
    print('key = {:<10}, value type = {}'.format(k, type(v)))

print()
print('key = {:<10}, value type = {}'.format('int', type(jcont['number'][0]['int'])))
print('key = {:<10}, value type = {}'.format('float', type(jcont['number'][1]['float'])))

 

 

결과는 아래와 같다.

 

 

jcont type =  <class 'dict'>
jcont len =  6 

key = object    , value type = <class 'str'>
key = array     , value type = <class 'str'>
key = string    , value type = <class 'str'>
key = number    , value type = <class 'list'>
key = true      , value type = <class 'bool'>
key = false     , value type = <class 'bool'>

key = int       , value type = <class 'int'>
key = float     , value type = <class 'float'>

 

json.org엔 JSON 파일 포맷을 그림으로도 설명해 주니 좀 더 쉽게 이해될 듯하다.

 

출처 : json.org