It depends on what you're wanting to use it for. If you're just trying to save it, you should use pickle
(or, if you’re using CPython 2.x, cPickle
, which is faster).
>>> import pickle
>>> pickle.dumps({'foo': 'bar'})
b'x80x03}qx00Xx03x00x00x00fooqx01Xx03x00x00x00barqx02s.'
>>> pickle.loads(_)
{'foo': 'bar'}
If you want it to be readable, you could use json
:
>>> import json
>>> json.dumps({'foo': 'bar'})
'{"foo": "bar"}'
>>> json.loads(_)
{'foo': 'bar'}
json
is, however, very limited in what it will support, while pickle
can be used for arbitrary objects (if it doesn't work automatically, the class can define __getstate__
to specify precisely how it should be pickled).
>>> pickle.dumps(object())
b'x80x03cbuiltins
object
qx00)x81qx01.'
>>> json.dumps(object())
Traceback (most recent call last):
...
TypeError: <object object at 0x7fa0348230c0> is not JSON serializable
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…