IVS/Python 프로그래밍

[JSON] Encoding/ Decoding, JSON 파일 파싱하기

코곰_ 2024. 12. 18. 10:59

 

I. 인코딩과 디코딩

(Python 기준)

Encoding

Python 객체를 JSON Data로 쓰는 동작

 

Decoding

읽은 JSON Data를 Python 객체로 저장

import json

a = dict()
a['name'] = 'sanghi'
a['price'] = 4900
a['brand'] = 'mcdonald'

# b는 json(인코딩)
b = json.dumps(a, indent=4) # indent : formatting
# c는 딕셔너리(디코딩)
c = json.loads(b)
print(c)

 

 

 

파일 전체를 읽어서 출력/ 저장하기

# 읽은 파일 출력하기
f1 = open('mc.json', 'r')
f2 = open('output.txt', 'w')

txt = f1.read()
f2.write(txt)
print(txt)

f2.close()
f1.close()
# 읽은 파일 저장하기
f1 = open('mc.json', 'r')
f2 = open('output.txt', 'w')

txt = ''

with open('mc.json', 'r') as f1:
    txt = f1.read()

with open('output.txt', 'w') as f2:
    f2.write(txt)

f2.close()
f1.close()

 

 

 

 

 

[과제] JSON Decoding 후 출력

  • 파일 출력 -> output.txt
  • 1) window 객체에서 key만
  • 2) image 객체에서 value만
  • 3) text 객체에서 items 메서드를 사용해 key, value 세트 
  • 파일에 출력하기 
import json
txt = ''

with open('mc.json', 'r') as f1:
    txt = f1.read()

# json을 dict로 디코딩
di = json.loads(txt)

with open('output.txt', 'w') as f2:
    f2.write(' '.join(str(x) for x in di["widget"]["window"].keys()) + '\n')
    f2.write(' '.join(str(x) for x in di["widget"]["image"].values()) + '\n')
    f2.write(' '.join(str(x) for x in di["widget"]["text"].items()))

# string만 출력가능 !
# print(di["widget"]["window"].keys())
# print(di["widget"]["image"].values())
# print(di["widget"]["text"].items())

 

output.txt

title name width height
Images/Sun.png sun1 250 250 center
('data', 'Click Here') ('size', 36) ('style', 'bold') ('name', 'text1') ('hOffset', 250) ('vOffset', 100) ('alignment', 'center') ('onMouseUp', 'sun1.opacity = (sun1.opacity / 100) * 90;')

 

 

 

 

 

II. JSON 파일 파싱하기

Awesome JSON Datasets
아래 링크에서 다운
https://github.com/jdorfman/awesome-json-datasets

 

import json
import requests # 데이터를 응답받기 위해 사용하는 모듈

url = "http://api.tvmaze.com/singlesearch/shows?q=narcos&embed=episodes"
r = requests.get(url)
print(r.text) # json객체로 프린트