Custom Class Serialization in Python

the question arose about serializing the classes that I defined. I have several classes, for example

class Foo:
     def __init__(self, x, y):
          self.x = x, self.y = y

     def toDict(self):
          return dict(Foo = dict(x = self.x, y = self.y))

then a class that can contain several Foos, such as:

class Bar:
     def __init__(self):
          self.foos = [Foo(a, b), Foo(1, 2)]

While this is a gross simplification of the real structure (it becomes much, much more nested than this), this is a pretty decent overview. The actual data for this comes from a pseudo-XML file without any real structure, so I wrote the parser according to the specification provided to me, so now I have all the data in the series of classes that I defined, with the actual structure.

, , , , JSON, ( Python, ).

Foo, toDict(), , , , , , Bar, Foos.

? - /codefest , , . JSON Python, ( - ), json.dump().

, - .

, T.J.

+3
3

. -:

, , .

  • , ? , , , dict s:

    root = {
        "foo1": { "bar1": "spam", "bar2": "ham"},
        "foo2": { "baz1": "spam", "baz2": "ham"},
    }
    

    .

, , , . BaseNode, ? , .

  • BaseNode.serialise, , serialise . ; , .

    json JSONEncoder .

    >>> import json
    >>> class ComplexEncoder(json.JSONEncoder):
    ...     def default(self, obj):
    ...         if isinstance(obj, complex):
    ...             return [obj.real, obj.imag]
    ...         return json.JSONEncoder.default(self, obj)
    ...
    >>> dumps(2 + 1j, cls=ComplexEncoder)
    '[2.0, 1.0]'
    >>> ComplexEncoder().encode(2 + 1j)
    '[2.0, 1.0]'
    >>> list(ComplexEncoder().iterencode(2 + 1j))
    ['[', '2.0', ', ', '1.0', ']']
    
+5

- JSON, Pickle .

0

, jsonpickle package - json.

0

Source: https://habr.com/ru/post/1772881/


All Articles