How do I pickle into a file with a structure?

2,154 views
Skip to first unread message

dbbd

unread,
Apr 24, 2010, 5:12:03 AM4/24/10
to jsonpickle
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

--
You received this message because you are subscribed to the Google Groups "jsonpickle" group.
To post to this group, send email to jsonp...@googlegroups.com.
To unsubscribe from this group, send email to jsonpickle+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/jsonpickle?hl=en.

John Paulett

unread,
Apr 24, 2010, 12:40:08 PM4/24/10
to jsonp...@googlegroups.com
jsonpickle itself does not implement the ability to pretty print and
currently does not pass any arguments to the various backends to tell
them to do so (although I would gladly accept a patch for this,
http://github.com/jsonpickle/jsonpickle).

A work around is a little ugly, but works:
    import json, jsonpickle
    print json.dumps(json.loads(jsonpickle.encode({"a": 1})), indent=4)

The json module docs also mention json.tool:
    echo '{"json":"obj"}' | python -mjson.tool

John

David Aguilar

unread,
Apr 24, 2010, 6:58:35 PM4/24/10
to jsonp...@googlegroups.com
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
Reply all
Reply to author
Forward
0 new messages