파이썬의 사전은 키-값쌍의 형태로 데이터를 구분하여 저장할 수 있고, 사전의 값이 될 수 있는 타입은 제약이 없기 때문에 중첩된 형태의 사전을 만드는 것도 가능하다. 만약 사전의 모든 키가 문자열이라면 사전을 JSON 데이터로 변환할 수 있다.
JSON은 자바스크립트에서, 자바스크립트 객체로 바로 변환할 수 있다. 따라서 자바스크립트에서는 root.somekey.nestedkey와 같은 식으로 객체 속성으로 접근해서 특정 위치의 값을 액세스하는 것이 가능하다는 말이다. 이에 반해 파이썬에서 JSON은 사전으로 파싱되고, 같은 데이터에 접근하기 위해서는 root[‘somekey’][‘nestedkey’] 와 같은 식으로 접근해야 한다.
이것을 자바스크립트에서처럼 root.somekey.nestedkey와 같이 액세스하기 위해서 간단한 래퍼 클래스를 하나 작성했다. 여기에 JSON과 호환되는 사전을 던져주면 객체처럼 . 문법을 써서 하위 속성을 액세스할 수 있다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/local/bin/python | |
#-*-coding:utf-8 | |
#filename:softDict.py | |
''' | |
softDict | |
copyright 2013. All right reserved to sooop. | |
''' | |
class SoftDict: | |
''' | |
Make data in dict to access object's property convention. | |
''' | |
def __init__(self, user_dict): | |
self._user_dict = user_dict | |
self._parse() | |
def _parse(self): | |
for key in self._user_dict.iterkeys(): | |
value = self._user_dict[key] | |
if type(value) == dict: | |
value = SoftDict(value) | |
setattr(self, key, value) | |
def main(): | |
a = { "meta":{"name":"a", "msg":"OK"},"res":"google"} | |
b = SoftDict(a) | |
print b.meta.msg | |
if __name__ == '__main__': | |
main() |