Created
April 18, 2014 07:05
-
-
Save lxneng/11028593 to your computer and use it in GitHub Desktop.
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/bin/env python | |
# encoding: utf-8 | |
class DictToObject(object): | |
def __init__(self, dictionary): | |
def _traverse(k, v): | |
if isinstance(v, dict): | |
return k, DictToObject(v) | |
elif isinstance(v, list): | |
# fix TypeError: unhashable type: 'list' | |
return k, tuple(v) | |
else: | |
return k, v | |
object_dict = {_traverse(k, v) for k, v in dictionary.items()} | |
self.__dict__.update(object_dict) | |
if __name__ == '__main__': | |
review_dict = { | |
"data": { | |
"product_id": "B00JLAJNEO", | |
"user_name": "け殇之吟か", | |
"review_content": "找到了好喝的酒,也是自己蛮喜欢的一款,物美价廉", | |
"avg_rating": 5, | |
"review_title": "物美价廉", | |
"review_created_at": "2014-04-13T00:00:00", | |
"user_id": "A1G0FHXLTMZILH" | |
}, | |
"time": "1397533940211", | |
"ok": True, | |
"errs": [] | |
} | |
review = DictToObject(review_dict) | |
assert review.data.product_id == 'B00JLAJNEO' | |
assert review.errs == () | |
print('review.data.username = %s ' % review.data.user_name) | |
print('review.data.username =', review.data.user_name) | |
# Notice: in python 2x out put is a tuple |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment