Python YAML 사용
pip install pyyaml
JSON과 유사하게 YAML은 키와 값을 가지고 있지만, 날짜와 시간 같은 데이터 타입을 더 많이 처리합니다. 표준 파이선 라이브러리는 아직 YAML 처리를 지원하고 있지 않습니다. 그래서 yaml이라는 써드파티 라이브러리를 설치합니다. load()는 YAML 문자열을 파이썬 데이터로, dump()는 그 반대의 기능을 수행합니다.
다음은 캐나다 시인 제임스 매킨타이어(James McIntyre)의 정보와 그의 두 시가 담신 mcintyre.yaml파일입니다.
name:
first: James
last: McIntyre
dates:
birth: 1828-05-25
death: 1906-03-31
details:
bearded: true
themes: [cheese, Canada]
books:
url: http://www.gutenberg.org/files/36068/36068-h/36068-h.htm
poems:
- title: 'Motto'
text: |
Politeness, perseverance and pluck,
To their possessor wil lbring good luck.
- title: 'Canadian Charms'
text: |
Here industry is not in vain,
For we have bounteous crops of grain,
And you behold on every field
Of grass and roots abundant yield, But after all the rgeatest charm
Is the snug home upon the farm,
And stone walls now keep cattle warm.
true, false, on, off와 같은 값은 부울형으로 변환됩니다. 정수와 문자열도 파이썬의 타입으로 변환됩니다. 다른 구문들은 리스트와 딕셔너리를 생성합니다.
import yaml
with open('mcintyre.yaml', 'rt') as fin:
text = fin.read()
data = yaml.load(text)
data['details']
len(data['poems'])
{‘themes’: [‘cheese’, ‘Canada’], ‘bearded’: True}
2
YAML파일에 맞게 생성된 자료구조는 한 레벨 더 들어가 있습니다. 딕셔너리/리스트/딕셔너리 참조로 다음과 같이 두 번째 시의 제목을 얻을 수 있습니다.
data['poems'][1]['title']
#'Canadian Charms'
주의할 점은, PyYAML은 문자열에서 파이선 객체를 불러올 수 있으나 위험합니다. 신뢰할 수 없는 YAML을 불러온다면 load() 대신 safe_load()를 사용하세요. 아직까지는 항상 safe_load()를 사용하는 것이 좋습니다. 루비 온 레일즈 플랫폼에서 보호받을 수 없는 YAML 로딩의 절충안에 대한 글(war is peace)을 읽어보세요.
https://infsafe.tistory.com/22?category=776554