In Python code, if we want to serialize and deserialize data using a Class, we might augment the execution in a common way, as in this example:

#! /usr/bin/env python
# _*_ coding: UTF-8 _*_


class Data:
    params: None


data = [
    {
        'params': 'Medusa'
    },
    {
        'params': 0}]Copy the code

Way if we want to put the data in the data instance of an array, you may need to directly to the data as an example, and the instance objects loaded in the list, of course, you can make for loop for instance and add to the list of a statement in advance, then you may think of the generator, more simple, can achieve this requirement, So let’s think about how we can restore our list object to data.

In Python code, of course, we can implement it, but it’s probably not as elegant in the way it’s implemented.

Here’s what we need to do:

python -m pip install attrs
python -m pip install cattrs
Copy the code

Install attrs and cattrs libraries. How do we use them? See the examples:

#! /usr/bin/env python
# _*_ coding: UTF-8 _*_
from attr import attrs, attrib
from cattr import structure, unstructure


@attrs
class Data:
    params = attrib()


data = {
    'params': 'Medusa',
}

instance = structure(data, Data)
json = unstructure(instance)
Copy the code

Let’s print the instance and json values:

# instance:
Data(params='Medusa')

# json:
{'params': 'Medusa'}
Copy the code

And when we use instance.params we get Medusa. Do you know how to serialize and deserialize between objects? Yes, of course, you may have a better library, welcome to share your comments