JSONPickle with SQLAlchemy objects

658 views
Skip to first unread message

t00f

unread,
Jun 3, 2011, 7:39:35 AM6/3/11
to jsonpickle
Hi guys,

First, I would like to thank you for the very useful jsonpickle
module.

I am trying to use your library in order to encode / decode SQLAlchemy
objects. JSON giving by the pickler.encode(obj, unpicklable=False)
method always give me an additional key named "_sa_instance_state".
This key provides a complete information about the object but does not
really make sense to be shown in my JSON representation.

For exemple, if I have a Person object (id, name) :


>>> p = Person('XXXXX')
>>> jsonpickle.encode(p, unpicklable=False)
'{"id": "XX", "name": "XXXXX", "_sa_instance_state": {"py/state":
{"instance": {"py/ref": "/"}, "callables": {}, "parents":
{"173984236": true}, "modified": true, "committed_state": {"code":
{"name": "NEVER_SET"}, "name": {"name": "NO_VALUE"}}}}}'

I am looking for a solution to remove this entry. I checked the source
code of jsonpickle and found that the flatten method pop out some
stuff. Is there any way to tell the library which keys has to be
deleted ?
I don't really want to fork the library, but I am thinking about
something like a method to pass a list of keywords to avoid keeping in
the JSON representation.

What do you think about this problem ? Do you have any current
solution to deal with it ?

Thanks for your time,

Best regards,

t00f

John Paulett

unread,
Jun 4, 2011, 8:45:51 PM6/4/11
to jsonp...@googlegroups.com
It does seem like jsonpickle is operating properly, since it the
_sa_instance_state is part of the SQLAlchemy object.

One option may be to post-process the JSON output:

>>> encoded = jsonpickle.encode(p, unpicklable=False)
>>> data = json.loads(encoded)
>>> del data['_sa_instance_state'] if '_sa_instance_state' in data
>>> json.dumps(data)

This is a bit of a pain, thus another option may be to write a custom
handler (BaseHandler subclass) that deletes the _sa_instance_state:
https://github.com/jsonpickle/jsonpickle/blob/master/jsonpickle/handlers.py

> --
> 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.
>
>

Reply all
Reply to author
Forward
0 new messages