From f936394b555ada6f466eb32b47890c8cbe470bbe Mon Sep 17 00:00:00 2001 From: acevest Date: Wed, 3 Dec 2014 18:41:23 +0800 Subject: [PATCH] add dict2object.py --- learn/python/dict2object.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100755 learn/python/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 -- 2.44.0