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

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

 

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

 

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

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

 

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들을 볼수 있습니다.

 

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 pari의 컬렉션(collection)
  • 값(value)들의 list

Slide4.JPG

 

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

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

 

JSON 결과 처리 - 전체 예제

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

 

# 이 코드는 Python에서 Computer Vision API를 호출하는 방법을 보여줍니다.
# Computer Vision의 Analyze Image 메서드 대한 문서는 여기에서 찾을 수 있습니다.
# https://westus.dev.cognitive.microsoft.com/docs/services/5adf991815e1060e6355ad44/operations/56f91f2e778daf14a499e1fa

# SQLER 강좌의 내용 https://www.sqler.com/board_CSharp/1095782 을 참조하세요.

# requests 라이브러리를 사용하여 Python에서 간단하게 REST API 호출을 진행합니다.
import requests

# 웹 서비스의 응답(Response)를 처리하려면 json 라이브러리가 필요합니다.
import json

# 아래 Vision_service_address를 자신에게 할당된 Computer Vision API 서비스의 주소로 수정해야 합니다. 
# 유료 가입 계정과 7일 체험 계정의 endpoint가 다를 수 있습니다. 맨 뒤의 "/v2.0/"을 확인하세요.
vision_service_address = "https://westcentralus.api.cognitive.microsoft.com/vision/v2.0/" 

# 호출하려는 API 함수의 이름을 주소에 추가합니다.
address = vision_service_address + "analyze"

# analyze image 함수의 문서에 따르면 세 가지의 Optional(선택적) 파라미터가 있습니다 : language, details, visualFeatures 파라미터
parameters  = {'visualFeatures':'Description,Color',
               'language':'en'}

# SUBSCRIPTION_KEY를 자신의 Computer Vision 서비스의 키로 수정하세요.
subscription_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxx"

# 분석할 이미지가 포함된 파일을 열어서 파일 오브젝트로 가져옵니다.
image_path = "./TestImages/PolarBear.jpg"
image_data = open(image_path, 'rb').read()

# analyze image 함수 문서에서 기술한대로, HTTP 헤더에 구독 키와 content-type을 지정합니다.
# content-type 값은 "application/octet-stream" 입니다.
headers    = {'Content-Type': 'application/octet-stream',
              'Ocp-Apim-Subscription-Key': subscription_key}

# analyze image 함수 문서에서 가이드 하는 것처럼, HTTP POST 방식으로 함수를 호출합니다.
response = requests.post(address, headers=headers, params=parameters, data=image_data)

# HTTP 호출에서 오류가 생기면, 예외를 발생 시킵니다.
response.raise_for_status()

# 리턴 받은 JSON 결과를 출력합니다.
results = response.json()
print(json.dumps(results))

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 reqeusts 코드
# 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 reqeusts 코드
# color 키에서 dominantColorBackground 값을 출력합니다.
print()
print('dominantColorBackground')
print(results['color']['dominantColorBackground'])

 

Slide6.JPG

 

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

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

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

 

Slide7.JPG

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

 

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

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

... # API reqeusts 코드
# 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의 변환은 정말 많이, 자주 쓰이니 잘 정리해 두시면 유용하실겁니다.

 

수고 많으셨습니다.

 

참고자료

개발자 커뮤니티 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 2023년 1월 - SQLER의 업데이트 강좌 리스트 코난(김대우) 2023.01.02 1250
Notice Python 무료 강좌 - 기초, 중급, 머신러닝(2021년 1월 업데이트) 코난(김대우) 2021.01.01 1161
96 Python 중급 강좌 - 2. 람다(Lamda) file 코난(김대우) 2021.01.03 267
95 Python 중급 강좌 - 1. Python 스타일 가이드: 서식(Formatting)과 린팅(Linting) file 코난(김대우) 2021.01.02 484
94 Python 초급 강좌 목차 - 19. 코드에서 중요한 키(패드워드) 관리 - dotenv 코난(김대우) 2021.01.02 494
93 Python 초급 강좌 목차 - 18. 데코레이터(Decorators) 코난(김대우) 2021.01.02 176
» Python 초급 강좌 목차 - 17. JSON 데이터 처리 file 코난(김대우) 2021.01.02 487
91 Python 초급 강좌 목차 - 16. 외부 웹서비스 API 호출 file 코난(김대우) 2021.01.02 562
90 Python 초급 강좌 목차 - 15. 패키지(Package): import, pip 코난(김대우) 2021.01.02 167
89 Python 초급 강좌 목차 - 14. 함수 파라미터(Parameter) 코난(김대우) 2021.01.02 164
88 Python 초급 강좌 목차 - 13. 함수(Function) 코난(김대우) 2021.01.02 198
87 Python 초급 강좌 목차 - 12. 반복문(Loop): for, while 코난(김대우) 2021.01.02 137
86 Python 초급 강좌 목차 - 11. 컬렉션(Collection): list, array, dictionary file 코난(김대우) 2021.01.02 177
85 Python 초급 강좌 목차 - 10. 조건문(Condition):3 복잡한 조건 처리 코난(김대우) 2021.01.01 152
84 Python 초급 강좌 목차 - 9. 조건문(Condition):2 다중 조건 처리 코난(김대우) 2021.01.01 175
83 Python 초급 강좌 목차 - 8. 조건문(Condition):1 (IF-ELSE) 코난(김대우) 2021.01.01 159
82 Python 초급 강좌 목차 - 7. 에러 핸들링(Error Handling) file 코난(김대우) 2021.01.01 178
81 Python 초급 강좌 목차 - 6. 날짜와 시간 데이터 처리 코난(김대우) 2021.01.01 198
80 Python 초급 강좌 목차 - 5. 숫자(Numeric) 데이터 처리 코난(김대우) 2021.01.01 148
79 Python 초급 강좌 목차 - 4. 문자열(String) 데이터 처리 코난(김대우) 2021.01.01 194
78 Python 초급 강좌 목차 - 3. 주석(Comments) 코난(김대우) 2021.01.01 168
77 Python 초급 강좌 목차 - 2. Print 구문 file 코난(김대우) 2021.01.01 280





XE Login