I love a more generic way to do this job. Gluing together python objects on the fly and serializing them to json and vice versa getting a JSON string an make a "Value-Container"-object out of it (without methods etc.) - I wonder how programmers can live without :-)
Maybe not the best code in the world and please make your suggestions, but I am doing it for 7 years now that way (runs in jython as well, performance also "ok"):
(please debug to see the structure of "po1" at the end):
# coding: UTF-8
import json
import types
def obj2dict(pp):
if type(pp) is types.TupleType:
olist=[]
for p in pp:
olist.append(obj2dict(p))
return tuple(olist)
if type(pp) is types.ListType:
olist=[]
for p in pp:
olist.append(obj2dict(p))
return olist
if type(pp) is types.DictionaryType:
odict={}
for k,val in pp.items():
odict[k]=obj2dict(val)
return odict
if type(pp) is types.InstanceType:
odict={}
for m in pp.__dict__:
val=getattr(pp,m)
odict[m]=obj2dict(val)
return odict
for m in dir(pp):
if not m.startswith("_"):
val=getattr(pp,m)
odict[m]=obj2dict(val)
return odict
return pp
class CONT:pass
def toFloat(inp):
return float(inp.replace(",","."))
def dict2obj(pp):
if type(pp) is types.ListType:
olist=[]
for p in pp:
olist.append(dict2obj(p))
return olist
if type(pp) is types.DictionaryType:
oinst=CONT()
for (k,v) in pp.items():
val=dict2obj(v)
setattr(oinst,k,val)
return oinst
try:
pp=toFloat(pp)
except:pass
return pp
def dumps(pp):
return json.dumps(obj2dict(pp)) #,ensure_ascii=False)
def loads(pp):
return dict2obj(json.loads(pp)) #,ensure_ascii=False))
if __name__ == "__main__":
jstring="""{
"cars" : [{
"model" : " BMW",
"gas" : 100
},
{
"model" : "LADA",
"gas" : 150
},
{
"model" : "SUZUKI",
"gas" : 70
}]
}"""
po1=loads(jstring)
po=CONT()
po.model="Toyota"
po.gas=88
print dumps(po)