Python/Python Programming

[Python] 파이썬 requests 모듈로 json 처리하기

Pydole 2018. 5. 5. 17:33

 

JSON은 자바스크립트에서 데이터 객체를 표한하는 방법

 

간결하고, 가벼워서 데이터 전송에 많이 쓰인다.

 

파이썬(python)으로 JSON 데이터를 받아서 사전(Dict) 형태로 변형해서 사용할 수 있다.

 

 

 

 

파이썬 requests 모듈을 이용하여 json 데이터형식 처리하기

 

 

json Testing Site : https://jsonplaceholder.typicode.com/users

 

JSONPlaceholder - Fake online REST API for developers

Intro JSONPlaceholder is a free online REST API that you can use whenever you need some fake data. It's great for tutorials, testing new libraries, sharing code examples, ... Example Run this code in a console or from any site: fetch('https://jsonplacehold

jsonplaceholder.typicode.com

 

위 JSON 테스트 사이트는 ID, usename, email 등을 JSON으로 제공해주는 페이지인데 , JSON 데이터를 받아서 사전형태

로 변경이 가능하다. 

 

 

import requests

s = requests.Session()
r = s.get('https://jsonplaceholder.typicode.com/users')

for x in r.json():      # json → dict
   print(x['username'])

print(type(x))
-------------------------------------------------------
Bret
Anton
Sama
Karia
Kamr
Leop
Elwy
Maxi
Delp
Moria
<class 'dict'>