2023년 6월 업데이트

 

안녕하세요. SQLER의 코난 김대우입니다. 

이번 강좌에서는, Python 초급 강좌 목차 - 17. JSON 데이터 처리를 진행토록 하겠습니다.

 

SQLER에서 진행되는 전체 Python / 머신러닝 강좌 목록

 

코드를 실행하기 위해서는, vscode에서 새로운 파일을 만들고 실행하시면 됩니다.

예를 들어, 17_json.py를 생성하고 코드를 실행합니다.

 

 

 

TL;DR

JSON의 구조에 대해 깊이있게 살펴보고, Python json 모듈로 JSON 데이터에 접근해 필요한 정보를 추출하는 방법을 코드로 확인합니다. 또한 Python dictionary 데이터형을 JSON으로 변환하는 방안도 리뷰합니다.
 

 

Python 초급 강좌 목차 - 17. JSON 데이터 처리

지난 개발자 커뮤니티 SQLER.com - Python 초급 강좌 목차 - 16. 외부 웹서비스 API 호출 강좌를 통해 웹 서비스에서 API를 호출해 결과를 출력하는 과정을 진행했습니다. 이번 강좌에서는 출력된 결과인 JSON 결과를 살펴보면서 JSON에 대해서 알아보는 시간을 가지도록 하겠습니다.

 

JSON이란 무엇이고 어떻게 사용되나요?

JSON은 표준 데이터 형식으로 수많은 서비스 간 데이터를 주고받을 때 사용되는 형식입니다. 많은 웹서비스의 API가 JSON, JavaScript Object Notation으로 데이터를 리턴합니다. JSON은 사람이 읽을 수 있고 코드로 구문을 분석하거나 생성할 수 있는 표준 형식입니다.

 

Slide2.JPG

 

샘플 JSON 결과

{
  "color": {
    "dominantColorForeground": "White",
    "dominantColorBackground": "White",
    "dominantColors": [
      "White"
    ],
    "accentColor": "595144",
    "isBwImg": false,
    "isBWImg": false
  },
  "description": {
    "tags": [
      "bear",
      "polar",
      "animal",
      "mammal",
      "water",
      "outdoor",
      "large",
      "walking",
      "snow",
      "standing"
    ],
    "captions": [
      {
        "text": "a polar bear in the water",
        "confidence": 0.7933424407633173
      }
    ]
  },
  "requestId": "0231629e-6ae6-48e9-93c5-5bd6fe0fcf31",
  "metadata": {
    "height": 221,
    "width": 220,
    "format": "Jpeg"
  }
}

 

샘플로 출력한 결과입니다.

 

이렇게 보통 JSON 결과는 길게 나열되어 사람이 알아보기 불편합니다. 여러 JSON linting 도구를 이용해 읽기 쉽게 포맷팅 할 수 있습니다. 다음 웹 사이트에서 여러 JSON Linter들을 볼 수 있습니다.

또는 pprint를 이용해 처리할 수도 있습니다.

 

import json
import pprint

response_data = '{"color": {"dominantColorForeground": "White", "dominantColorBackground": "White", "dominantColors": ["White"], "accentColor": "595144", "isBwImg": false, "isBWImg": false}, "description": {"tags": ["bear", "polar", "animal", "mammal", "water", "outdoor", "large", "walking", "snow", "standing"], "captions": [{"text": "a polar bear in the water", "confidence": 0.7933424407633173}]}, "requestId": "0231629e-6ae6-48e9-93c5-5bd6fe0fcf31", "metadata": {"height": 221, "width": 220, "format": "Jpeg"}}'
results = json.loads(response_data)

# 보기 어렵게 출력됩니다.
print(results)

# 포맷되어 출력됩니다.
pprint.pprint(results)

 

 

JSON linting 결과

이런 linter 서비스를 이용하면, 이런 형태로 잘 정돈되어 출력됩니다.

{
  "color":  {
    "dominantColorForeground":  "White",
     "dominantColorBackground":  "White",
     "dominantColors":  [
      "White"
    ],
     "accentColor":  "595144",
     "isBwImg":  false,
     "isBWImg":  false
  },
   "description":  {
    "tags":  [
      "bear",
       "polar",
       "animal",
       "mammal",
       "water",
       "outdoor",
       "large",
       "walking",
       "snow",
       "standing"
    ],
     "captions":  [
      {
        "text":  "a polar bear in the water",
         "confidence":  0.7933424407633173
      }
    ]
  },
   "requestId":  "0231629e-6ae6-48e9-93c5-5bd6fe0fcf31",
   "metadata":  {
    "height":  221,
     "width":  220,
     "format":  "Jpeg"
  }
}

 

이렇게, 결과를 좀 더 수월하게 확인 가능합니다.

 

JSON의 구조

JSON은 두 가지 구조로 구축됩니다.

  • key/value pair의 컬렉션(collection)
  • 값(value)들의 list

Slide4.JPG

 

Python에는 JSON을 인코딩하고 디코딩하는 데 도움이 되는 json 모듈이 포함되어 있습니다.

이 모듈을 이용해 JSON 결과를 파싱해 원하는 형태로 출력 가능합니다.

 

JSON 결과 처리 - 전체 예제

아래 코드를 실행해 결과를 보시면서, 함께 이후 강좌를 살펴보시면 더 이해가 쉬우실 겁니다.

 

import json

response_data = '{"color": {"dominantColorForeground": "White", "dominantColorBackground": "White", "dominantColors": ["White"], "accentColor": "595144", "isBwImg": false, "isBWImg": false}, "description": {"tags": ["bear", "polar", "animal", "mammal", "water", "outdoor", "large", "walking", "snow", "standing"], "captions": [{"text": "a polar bear in the water", "confidence": 0.7933424407633173}]}, "requestId": "0231629e-6ae6-48e9-93c5-5bd6fe0fcf31", "metadata": {"height": 221, "width": 220, "format": "Jpeg"}}'
results = json.loads(response_data)

print('requestId')
print(results['requestId'])

print('dominantColorBackground')
print(results['color']['dominantColorBackground'])

print('first_tag')
print(results['description']['tags'][0])

for item in results['description']['tags']:
    print(item)

print('caption text')
print(results['description']['captions'][0]['text'])

 

 

JSON 결과에서 Key 이름으로 Value값을 추출

"key":"value" 형태로 구성된 결과에서 key 이름으로 value 값을 추출하려면, python에서 이렇게 실행합니다.

... # API requests 코드
# print the value for requestId from the JSON output
# JSON 결과에서 requestId 값을 출력합니다.
print()
print('requestId')
print (results['requestId'])

 

 

Slide5.JPG

 

Python으로 JSON nested key에서 subkey 추출

두 개 이상의 key가 중첩되어 있을 경우에는, 이렇게 key 이름을 추가 지정하면서 탐색해 subkey value를 가져옵니다.

... # API requests 코드
# color 키에서 dominantColorBackground 값을 출력합니다.
print()
print('dominantColorBackground')
print(results['color']['dominantColorBackground'])

 

Slide6.JPG

 

Python에서 나열되어 있는 JSON value 값 가져오기

나열되어 있는 JSON value들을 가져오려면, key 이름과 index 번호를 이용해 값을 가져옵니다.

... # API requests 코드
# description의 첫 번째 태그를 인쇄합니다.
print()
print('first_tag')
print(results['description']['tags'][0])

 

Slide7.JPG

이렇게 description/tags의 0번째 index값이 bear를 가져옵니다.

 

Python에서 나열되어 있는 모든 value 값 가져오기

또한 많이 사용되는 패턴으로, 나열되어 있는 JSON 키의 모든 value값을 가져오려면, 이렇게 loop를 이용합니다.

... # API requests 코드
# description에 있는 모든 태그를 인쇄합니다.
print()
print('all tags')
for item in results['description']['tags']:
    print(item)

 

Slide8.JPG

 

Python dictionary와 JSON

지난 컬렉션 강좌에서 소개해 드린 것처럼, Dictionary 데이터형과 JSON 형식은 유사합니다.

 

Python dictionary 데이터형으로 JSON 개체 생성

JSON 개체를 손쉽게 dictionary 데이터형에서 생성할 수 있습니다.

import json

# Dictionary 객체 생성
person_dict = {'first': 'Christopher', 'last':'Harrison'}
# 필요에 따라 dictionary에 key/value pair를 추가합니다.
person_dict['City']='Seattle'

# Dictionary를 JSON 객체로 변환
person_json = json.dumps(person_dict)

# JSON 객체 출력
print(person_json)

 

JSON subkey 구조 형식 생성

Python의 중첩된 Dictionary 데이터형을 이용해 JSON subkey 구조를 생성할 수 있습니다.

import json

# Dictionary 객체 생성
person_dict = {'first': 'Christopher', 'last':'Harrison'}
# 필요에 따라 dictionary에 key/value pair를 추가
person_dict['City']='Seattle'

# staff dictionary 생성
staff_dict ={}
# person_dict를 "Program Manager"로 값 설정
staff_dict['Program Manager']=person_dict
# Dictionary를 JSON 객체로 변환
staff_json = json.dumps(staff_dict)

# JSON 객체 출력
print(staff_json)

 

Python List 데이터를 JSON에 추가

Python list 데이터형을 dictionary에 추가하고, 이어서 dictionary를 JSON 형식으로 변환할 수 있습니다.

import json

# Dictionary 객체 생성
person_dict = {'first': 'Christopher', 'last':'Harrison'}
# 필요에 따라 dictionary에 key/value pair를 추가
person_dict['City']='Seattle'

# List 객체를 생성
languages_list = ['CSharp','Python','JavaScript']

# List 객체를 dictionary에 languages를 key로 추가 
person_dict['languages']= languages_list

# Dictionary를 JSON 객체로 변환
person_json = json.dumps(person_dict)

# JSON 객체 출력
print(person_json)

 

 

이외에도 수많은 JSON 관련 함수와 변환을 프로젝트에서 하시게 될 거에요.

Dictionary와 JSON의 변환은 정말 많이, 자주 쓰이니 잘 정리해 두시면 유용하실 겁니다.

 

수고 많으셨습니다.

 

 

파이썬 강좌 책 구매

강좌가 도움이 되셨다면, 책으로 구매 가능합니다. 책 판매 수익금은 전액 코딩 교육 사회공헌 활동에 기부되며, 아래 링크에서 구매하시면 더 많은 금액이 기부됩니다. 

 

책구매 링크: 챗GPT와 함께하는 파이썬 & 머신러닝 코딩 마스터 

파이썬-책구매링크.png

 

참고자료

개발자 커뮤니티 SQLER.com - Python 무료 강좌 - 기초, 중급, 머신러닝

c9-python-getting-started/python-for-beginners/17 - JSON at master · CloudBreadPaPa/c9-python-getting-started (github.com)

JSON

json — JSON encoder and decoder — Python 3.8.7 documentation

 

No. Subject Author Date Views
Notice SQL강좌: 챗GPT와 함께 배우는 SQL Server 무료 강좌 목차와 소개 (2023년 9월 업데이트) 코난(김대우) 2023.08.18 38455
Notice Python 무료 강좌 - 기초, 중급, 머신러닝(2023년 6월 업데이트) 코난(김대우) 2021.01.01 20748
98 Python 중급 강좌 - 4. 상속(Inheritance) 코난(김대우) 2021.01.03 344
97 Python 중급 강좌 - 3. 클래스(Class) 코난(김대우) 2021.01.03 403
96 Python 중급 강좌 - 2. 람다(Lamda) file 코난(김대우) 2021.01.03 545
95 Python 중급 강좌 - 1. Python 스타일 가이드: 서식(Formatting)과 린팅(Linting) file 코난(김대우) 2021.01.02 1099
94 Python 초급 강좌 목차 - 19. 코드에서 중요한 키(패스워드) 관리 - dotenv 코난(김대우) 2021.01.02 970
93 Python 초급 강좌 목차 - 18. 데코레이터(Decorators) 코난(김대우) 2021.01.02 343
» Python 초급 강좌 목차 - 17. JSON 데이터 처리 file 코난(김대우) 2021.01.02 821
91 Python 초급 강좌 목차 - 16. 외부 웹서비스 API 호출 file 코난(김대우) 2021.01.02 945
90 Python 초급 강좌 목차 - 15. 패키지(Package): import, pip 코난(김대우) 2021.01.02 411
89 Python 초급 강좌 목차 - 14. 함수 파라미터(Parameter) 코난(김대우) 2021.01.02 400
88 Python 초급 강좌 목차 - 13. 함수(Function) 코난(김대우) 2021.01.02 543
87 Python 초급 강좌 목차 - 12. 반복문(Loop): for, while 코난(김대우) 2021.01.02 324
86 Python 초급 강좌 목차 - 11. 컬렉션(Collection): list, array, dictionary file 코난(김대우) 2021.01.02 327
85 Python 초급 강좌 목차 - 10. 조건문(Condition):3 복잡한 조건 처리 코난(김대우) 2021.01.01 360
84 Python 초급 강좌 목차 - 9. 조건문(Condition):2 다중 조건 처리 코난(김대우) 2021.01.01 394
83 Python 초급 강좌 목차 - 8. 조건문(Condition):1 (IF-ELSE) 코난(김대우) 2021.01.01 362
82 Python 초급 강좌 목차 - 7. 에러 핸들링(Error Handling) file 코난(김대우) 2021.01.01 352
81 Python 초급 강좌 목차 - 6. 날짜와 시간 데이터 처리 코난(김대우) 2021.01.01 396
80 Python 초급 강좌 목차 - 5. 숫자(Numeric) 데이터 처리 코난(김대우) 2021.01.01 327
79 Python 초급 강좌 목차 - 4. 문자열(String) 데이터 처리 코난(김대우) 2021.01.01 433





XE Login