본문 바로가기
Python

[Python] 파이썬으로 JSON 데이터 다루기

by A6K 2022. 5. 14.

REST API를 사용하는 파이썬 프로그램을 작성할 때 JSON 데이터를 다루는 경우가 많다. 파이썬은 JSON 데이터를 다루기 위해 json 모듈을 내장하고 있다.

이번 포스트에서는 json 모듈을 이용해 JSON 데이터를 다루는 방법에 대해 정리해보겠다.

json.loads() - JSON 문자열 파싱

json 모듈의 loads() 함수를 이용해 JSON 문자열을 파싱해 사용할 수 있다.

import json

json_data = '''
{
    "mentor": {
        "Name" : "Tom",
        "Age" : 20
    },
    "mentee" : {
        "Name" : "Eric",
        "Age" : 13
    }
}
'''

json_obj = json.loads(json_data)

print(json_obj)
print("Mentor : " + json_obj['mentor']['Name'])
print("Mentee : " + json_obj['mentee']['Name'])

실행결과

{'mentor': {'Name': 'Tom', 'Age': 20}, 'mentee': {'Name': 'Eric', 'Age': 13}}
Mentor : Tom
Mentee : Eric

JSON 문자열을 loads() 함수의 인자로 넣어주면 파싱해서 dict 객체를 만들어 준다. 만들어진 dict 객체에 키 값을 입력하면서 JSON 객체 값을 따라내려갈 수 있다.

만약 JSON 문자열이 문법에 맞지 않는다면 loads() 함수에서 json.decoder.JSONDecodeError 가 발생한다.

import json

json_data = '''
[
    {
        "Name" : "Apple",
        "Color" : "Red",
        "price" : 1000
    },
    {
        "Name" : "Banana",
        "Color" : "Yellow",
        "price" : 500
    }
]
'''

json_obj = json.loads(json_data)

print(json_obj)
print("First fruit : " + json_obj[0]['Name'])
print("First fruit : " + json_obj[1]['Name'])

실행결과

[{'Name': 'Apple', 'Color': 'Red', 'price': 1000}, {'Name': 'Banana', 'Color': 'Yellow', 'price': 500}]
First fruit : Apple
First fruit : Banana

JSON 객체뿐만 아니라 JSON 객체의 리스트 역시 파싱 가능하다. JSON 객체의 리스트는 파싱하면 리스트 객체로 만들어주며 숫자 인덱스로 접근해서 JSON 객체를 참조할 수 있다.

json.load() - JSON 파일에서 읽기

json.load() 함수를 이용하면 JSON 데이터를 저장하고 있는 파일로부터 데이터를 읽어 파싱할 수 있다.

import json

with open('data.json') as f:
    json_obj = json.load(f)

print(json_obj)
print("Mentor : " + json_obj['mentor']['Name'])
print("Mentee : " + json_obj['mentee']['Name'])

만들어진 JSON 객체는 dict 혹은 list 객체이며 문자열로부터 만들어진 것과 동일하게 키 값이나 인덱스로 접근할 수 있다.

json 데이터 순회

파이썬 스크립트로 JSON 데이터를 처리할 때, JSON의 하위 항목들을 순회하면서 처리하는 경우가 많다. 이 경우 for 문을 이용해서 순회하면 된다.

import json

json_data = '''
[
    {
        "Name" : "Apple",
        "Color" : "Red",
        "price" : 1000
    },
    {
        "Name" : "Banana",
        "Color" : "Yellow",
        "price" : 500
    }
]
'''

json_list = json.loads(json_data)

for json_obj in json_list:
    print(json_obj)

실행결과

{'Name': 'Apple', 'Color': 'Red', 'price': 1000}
{'Name': 'Banana', 'Color': 'Yellow', 'price': 500}

JSON 리스트의 경우 순회를 하면 리스트에 있는 JSON 객체를 하나씩 참조하게 된다.

import json

json_data = '''
    {
        "Name" : "Banana",
        "Color" : "Yellow",
        "price" : 500
    }
'''

json_list = json.loads(json_data)

for json_obj in json_list:
    print(json_obj)

실행결과

Name
Color
price

JSON 객체를 순회하면 객체의 키 값들을 하나씩 참조하게 된다. 참조되는 키 값을 이용해서 JSON 객체에 접근, Value 값을 얻어오면 된다.

json.dumps() - JSON 데이터를 문자열로 출력

반대로 JSON 데이터를 문자열로 출력할 수도 있다. JSON 데이터를 문자열로 출력하기 위해 json.dumps() 함수를 이용하면 된다.

import json

json_data = {
    "mentor": {
        "Name" : "Tom",
        "Age" : 20
    },
    "mentee" : {
        "Name" : "Eric",
        "Age" : 13
    }
}

json_str = json.dumps(json_data)

print(json_str)

실행결과

{"mentor": {"Name": "Tom", "Age": 20}, "mentee": {"Name": "Eric", "Age": 13}}

문자열로 출력이 되지만 줄바꿈이 없이 한줄에 길게 나온다. 이 자체로 JSON 데이터이지만 가독성이 너무 안 좋기 때문에 사람이 보기 편한 스타일로 예쁘게 출력할 필요가 있다.

json.dumps() 함수의 indent 파라미터에 숫자를 넘기면 그 숫자만큼 들여쓰기가 되어 JSON 문자열을 출력해준다.

import json

json_data = {
    "mentor": {
        "Name" : "Tom",
        "Age" : 20
    },
    "mentee" : {
        "Name" : "Eric",
        "Age" : 13
    }
}

json_str = json.dumps(json_data, indent=2)

print(json_str)

실행결과

{
  "mentor": {
    "Name": "Tom",
    "Age": 20
  },
  "mentee": {
    "Name": "Eric",
    "Age": 13
  }
}

json.dump() - JSON 데이터를 파일로 쓰기

json.dump() 함수를 이용하면 JSON 데이터를 파일로 쓸 수 있다.

import json

json_data = {
    "mentor": {
        "Name" : "Tom",
        "Age" : 20
    },
    "mentee" : {
        "Name" : "Eric",
        "Age" : 13
    }
}

with open('data.json', 'w') as f:
    json.dump(json_data, f, indent=2)

XML을 JSON으로 변환하기

REST API에 따라 다르지만 일부 API는 XML로 데이터를 제공하는 경우가 있다. 이 경우 XML 데이터를 JSON 데이터로 변경해서 통합해야할 필요가 있을 수 있다.

XML 데이터를 파싱하기 위해서는 xmltodict 모듈을 이용하면 된다. 

import json
import xmltodict

xml_data = """
<pair>
  <mentor>
    <name>Tom</name>
    <age>20</age>
  </mentor>
  <mentee>
    <name>Eric</name>
    <age>13</age>
  </mentee>
</pair>
"""

xml_dict = xmltodict.parse(xml_data)
json_str = json.dumps(xml_dict, indent=2)

print(json_str)

실행결과

{
  "pair": {
    "mentor": {
      "name": "Tom",
      "age": "20"
    },
    "mentee": {
      "name": "Eric",
      "age": "13"
    }
  }
}

xmltodict 모듈은 기본 내장되어 있는 모듈이 아니므로 설치해야할 수 있다. xmltodict 모듈을 설치하기 위해서는 

$ pip install xmltodict

혹은

$ pip3 install xmltodict

를 수행하면 된다.

좀 더 자세한 내용은 파이썬 내장 모듈인 json 모듈의 매뉴얼을 살펴보도록 하자.


 

json — JSON encoder and decoder — Python 3.10.4 documentation

json — JSON encoder and decoder Source code: Lib/json/__init__.py JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 4627) and by ECMA-404, is a lightweight data interchange format inspired by JavaScript object literal syntax (

docs.python.org

 

파이썬 스크립트 작성에 도움되는 글 모음

파이썬으로 프로그램을 작성할 때 도움되는 글들을 모아본다. Python 문법 Python 모듈

hbase.tistory.com

 

댓글