import json data = { 'name' : 'ACME', 'shares' : 100, 'price' : 542.23 } json_str = json.dumps(data) data = json.loads(json_str) # Writing JSON data to file with open('data.json', 'w') as f: json.dump(data, f) # Reading data back with open('data.json', 'r') as f: data = json.load(f)
defserialize_instance(obj): d = { '__classname__' : type(obj).__name__ } d.update(vars(obj)) return d # Dictionary mapping names to known classes classes = { 'Point' : Point } defunserialize_object(d): clsname = d.pop('__classname__', None) if clsname: cls = classes[clsname] obj = cls.__new__(cls) # Make instance without calling __init__ for key, value in d.items(): setattr(obj, key, value) return obj else: return d
使用方法如下:
1 2 3 4 5 6 7 8 9 10 11
p = Point(2,3) s = json.dumps(p, default=serialize_instance) s '{"__classname__": "Point", "y": 3, "x": 2}' a = json.loads(s, object_hook=unserialize_object) a <__main__.Point object at 0x1017577d0> a.x 2 a.y 3