From: acevest Date: Wed, 3 Dec 2014 10:41:23 +0000 (+0800) Subject: add dict2object.py X-Git-Url: http://zhaoyanbai.com/repos/%22http:/www.isc.org/icons/zpipe.c?a=commitdiff_plain;h=f936394b555ada6f466eb32b47890c8cbe470bbe;p=acecode.git add dict2object.py --- diff --git a/learn/python/dict2object.py b/learn/python/dict2object.py new file mode 100755 index 0000000..2b3daa5 --- /dev/null +++ b/learn/python/dict2object.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# ------------------------------------------------------------------------ +# File Name: dict2object.py +# Author: Zhao Yanbai +# Wed Dec 3 18:40:09 2014 +# Description: none +# ------------------------------------------------------------------------ +import json + +js = json.loads('{"s" : "Hello World."}') + + + +def obj_dic(d): + top = type('new', (object,), d) + seqs = tuple, list, set, frozenset + for i, j in d.items(): + if isinstance(j, dict): + setattr(top, i, obj_dic(j)) + elif isinstance(j, seqs): + setattr(top, i, + type(j)(obj_dic(sj) if isinstance(sj, dict) else sj for sj in j)) + else: + setattr(top, i, j) + + return top + + +j = obj_dic(js) + + +print j.s