Saving and restoring a state objects in JSON files

#
# Save a visit state object to a JSON file.
#

import json

def vobj_to_dict(obj):
    res = {}
    res["type"] =  type(obj).__name__
    res["properties"] = {}
    for pname in dir(obj):
        if pname.startswith("Get"):
            pentry = pname[3].lower() + pname[4:]
            pvalue = getattr(obj, pname)()
            res["properties"][pentry] = pvalue
    return res

def vobj_from_dict(odict):
    res = globals()[odict["type"]]()
    print res
    for k,v in odict["properties"].items():
        if isinstance(v,list):
            v = tuple(v)
        setattr(res,k,v)
    return res

def vobj_to_json(obj,fname):
    json.dump(vobj_to_dict(obj), open(fname,"w"))

def vobj_from_json(fname):
    return vobj_from_dict(json.load(open(fname)))


#
# Example usage with the View3DAttributes state object. 
#

v3d = GetView3D()
vobj_to_json(v3d,"v3d.json")

print "original:"
print v3d
print

restored = vobj_from_json("v3d.json")

print "restored from file:"
print restored
SetView3D(restored)