1

I use jsonpickle for serializer when i selectall to database, i am going to convert list object to json when use jsonpickle for this i get this output:

Codes:

 Session = sessionmaker(bind=connect.ConnectorMySql())
                    ses = Session()
                    lst =  ses.query(pModel).all()
                    return lst

jsonpickle:

serialized_obj = jsonpickle.encode(lst[0])

output:

{"py/object": "Models.UserModel.", "sa_instance_state": {"py/object": "sqlalchemy.orm.state.InstanceState", "py/state": {"instance": {"py/id": 0}, "committed_state": {}, "class": {"py/type": "Models.UserModel."}, "manager": {"py/object": "sqlalchemy.orm.instrumentation.SerializeManager", "class": {"py/type": "Models.UserModel.Student"}}, "key": {"py/tuple": [{"py/type": "Models.UserModel.Student"}, {"py/tuple": [1]}]}, "expired_attributes": {"py/set": []}}}, "name": "ramin", "fullname": "eee", "password": "1234345", "id": 1}

but i need this format json:

{"name": "ramin", "fullname": "eee", "password": "1234345", "id": 1}

do you idea better for this work?

Ramin Farajpour Cami
  • 1,605
  • 3
  • 11
  • 21

2 Answers2

0

This is not what jsonpickle is for. pickle and jsonpickle are used to serialize an arbitrary Python object into some format so that it can later be deserialized into the exact same Python object. They are not used for serialization of objects according to a particular schema.

For your case, you have to write the serialization logic yourself. Example:

obj = lst[0]
serialized_obj = {k: getattr(obj, k) for k in ["name", "fullname", "password", "id"]}

You'll have to handle any special types as well. You can even get fancy and try to reflect what columns are on the model automatically.

By the way, is that passwords stored in plaintext I see?

univerio
  • 19,548
  • 3
  • 66
  • 68
0

Try defining __getstate__ and __setstate__ on your SQLAlchemy object as follows

def __getstate__(self):
    state = {}
    for k, v in self.__dict__.items():
        if k != '_sa_instance_state':
            state[k] = v
    return state

def __setstate__(self, d):
    self.__dict__ = d

jsonpickle will use these to pickle/depickle, and you don't store the _sa_instance_state which is internal book-keeping if I understand it correctly.

Some related info here: http://docs.sqlalchemy.org/en/latest/orm/extensions/mutable.html#supporting-pickling

EoghanM
  • 25,161
  • 23
  • 90
  • 123