如何使用jsonpickle排除序列化的特定字段? [英] How to exclude specific fields on serialization with jsonpickle?

查看:333
本文介绍了如何使用jsonpickle排除序列化的特定字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Flask的SQLAlchemy扩展。在使用jsonpickle序列化我的模型(也用于数据库操作)时,我想要忽略一些特定的属性。有没有一种方法可以让我设置这些规则?

SQLAlchemy向对象添加一个名为 _sa_instance_state 的属性。总之,我不希望这个字段在JSON输出中。

解决方案

你不能告诉默认的类pickler忽略某些东西,不。


$ b

jsonpickle does 支持 pickle 模块 __ getstate __ __ setstate __ 方法。如果你的类实现了这两个方法,则不管返回的是什么,然后用 jsonpickle 来表示状态。如果 __ getstate __ 不是 ,那么 jsonpickle 使用 __ dict __ 属性,所以你自己的版本只需要使用同一个字典,删除<$ c $

  def __getstate __(self):
state = self .__ dict __。copy()
del state ['_ sa_instance_state']
返回状态
$ b def __setstate __(self,state):
self .__ dict__。 update(state)

无论 __ getstate __ 如果添加 __ getstate __
>,则可以进一步处理,不需要担心在那里处理子对象。 code> __ setstate __ 不是一个选项,你也可以注册一个自定义序列化处理程序为你的班级;缺点是只要返回一个字典, __ getstate __ 可以离开,一个自定义处理程序将需要返回一个完全平坦的值。


I'm using SQLAlchemy extension with Flask. While serializing my models (which are also used for database operations) using jsonpickle, I want some specific attributes to be ignored. Is there a way that allows me to set those rules?

SQLAlchemy adds an attribute named _sa_instance_state to the object. In a word, I do not want this field to be in the JSON output.

解决方案

You cannot tell the default class pickler to ignore something, no.

jsonpickle does support the pickle module __getstate__ and __setstate__ methods. If your classes implement those two methods, whatever is returned is then used by jsonpickle to represent the state instead. Both methods do need to be implemented.

If __getstate__ is not implemented, jsonpickle uses the __dict__ attribute instead, so your own version merely needs to use that same dictionary, remove the _sa_instance_state key and you are done:

def __getstate__(self):
    state = self.__dict__.copy()
    del state['_sa_instance_state']
    return state

def __setstate__(self, state):
    self.__dict__.update(state)

Whatever __getstate__ returns will be processed further, recursively, there is no need to worry about handling subobjects there.

If adding __getstate__ and __setstate__ is not an option, you can also register a custom serialization handler for your class; the disadvantage is that while __getstate__ can get away with just returning a dictionary, a custom handler will need to return a fully flattened value.

这篇关于如何使用jsonpickle排除序列化的特定字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆