On Sat, Apr 24, 2010 at 02:12:03AM -0700, dbbd wrote:
> Writing a jsonpickle object to a file generates a single line file.
> How do I generate the file so that it is human readable (braces start
> a newline, indentation etc.)?
>
> Thanks,
> Dan
jsonpickle does allow you to set flags for encoding, but it is
backend-specific.
There are two ways to do it.
I recommend the 2nd because it keeps things scoped and does not
affect things on a global level. The first way is more
convenient, but it affects anything that might be using
jsonpickle. Hence, it's good for some situations, but not good
for library code where you don't typically want to have any
global side-effects.
Now, on to the code. This assumes you're using 'simplejson' as
your backend. If you want to use python2.6's 'json' module,
adjust accordingy. You might also need to add a call to
set_preferred_backend('json') if you have both installed.
# -- >8 --
#!/usr/bin/env python
import jsonpickle
obj = {'a': 1, 'b': 2, 'c': 3}
# Set the encoding options globally
jsonpickle.set_encoder_options('simplejson', indent=4)
print jsonpickle.encode(obj)
# Use a new instance of the plugin manager, thus avoiding any
# global side-effects
pluginmgr = jsonpickle.JSONPluginMgr()
pluginmgr.set_encoder_options('simplejson', indent=4)
print pluginmgr.encode(obj)
# -- >8 --
We should add a section to the documentation explaining
these details :)
--
David