New JSON encoding method proposal for custom objects

Burak Arslan burak.arslan at arskom.com.tr
Tue Dec 1 06:20:57 EST 2015


hey,

On 11/30/15 14:35, cescus92 at gmail.com wrote:
>
> Hello everyone and thank you for your interest!
>
> The Peter's code is very similar to what I think the default JSON encoder should be.
>
> The advantage of the method that I propose is that you should not care anymore about which encoder you're going to use even in case of different class instances. Imagine if you could just do
>
>   json.dumps({[1,2,3], Obj(), [DifferentObj()] })
>
>

FWIW, Spyne can to the exact same thing -- i.e. serialize an object
given its definition to whatever format you want. (currently xml, json,
yaml and msgpack are supported). Here's a json example:

>>> from spyne import *
>>> from spyne.util.dictdoc import get_object_as_json, get_json_as_object
>>> get_object_as_json([1,2,3], Array(Integer))
'[1, 2, 3]'
>>>
>>> from datetime import datetime
>>>
>>> class SomeObject(ComplexModel):
...     s = Unicode
...     i = Integer
...     dt = DateTime
...
>>> get_object_as_json(SomeObject(s='str', i=42, dt=datetime.now()),
complex_as=list)
'[42, "str", "2015-12-01T12:57:23.751631"]'
>>>
>>> get_json_as_object('[42, "str", "2015-12-01T12:55:21.777108"]',
SomeObject, complex_as=list)
SomeObject(i=42, s=u'str', dt=datetime.datetime(2015, 12, 1, 12, 55, 21,
777108))
>>>
>>>

More info: http://spyne.io

Best,
Burak

PS: The astute reader will notice that element order in SomeObject could
be totally random.

* In Python 3, we solve that by returning an odict() in the __prepare__
of the ComplexModel metaclass.
* In Python 2, we solve that by somehow getting hold of AST of the class
definition and deducing the order from there. Yes you read that right! I
know, it's horrible! Don't worry, it's turned off by default. We
recommend the workaround in [1] for Python 2. See [2] and [3] to see how
we integrated it.

[1]: http://spyne.io/docs/2.10/manual/03_types.html#complex
[2]: https://github.com/arskom/spyne/pull/313
[3]:
https://github.com/arskom/spyne/blob/2768c7ff0b5f58aa0e47859fcd69e5bb7aa31aba/spyne/util/meta.py




More information about the Python-list mailing list