-
Notifications
You must be signed in to change notification settings - Fork 37
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How can I easily skip certain attributes #70
Comments
Hi @dolfandringa! Apologies for the late answer, I normally respond sooner, but I couldn't. There actually is a way you can skip specific attributes from being dumped. You can use Let's say you have the following code: import logging
from jsons import JsonSerializable, dump
class MyClass(JsonSerializable):
def __init__(self):
self.a = 1
self.b = 2
self.log = logging.getLogger(__name__)
inst = MyClass() You can then serialize res1 = dump(inst, strip_attr='log')
res2 = dump(inst, strip_attr=('log', 'a')) Resulting in: {'a': 1, 'b': 2} for {'b': 2} Now since you are using class MyClass2(JsonSerializable.with_dump(strip_attr='log')):
def __init__(self):
self.a = 1
self.b = 2
self.log = logging.getLogger(__name__) What this does, is altering Now you can simply do: inst2 = MyClass2()
res3 = inst2.json Resulting in: {'a': 1, 'b': 2} for Extra noteBe aware that by using class MyClass(JsonSerializable.with_dump(strip_attr='log', fork=True)):
... As I'm writing this now, I'm thinking of changing the default behavior by setting FinallyYou were right that this was not properly documented. I will add |
I can't easily find in the docs how I can specify some attributes of my JsonSerializable class that I don't want to be serialized to JSON.
In the above case, how can I make self.log get skipped, without having to modify the
jsons.dumps
call? I want the control of what gets included in the JSON to be with the class, not the place wheredump(s/b)
is called. So I don't want to have to make them private (with '_') and addstrip_privates
todumps
. First of all, that would require modifying all dumps calls throughout my code, and secondly, it forces me to change my datamodel, which has consequences elsewhere in the app.Aside from this example where self.log clearly isn't serializable, and also wouldn't make sense to serialize, there may be other attributes that I want to skip as well. Is this easily possible with jsons? If so, can we add a FAQ question about it? (I'd be happy to contribute it)
The text was updated successfully, but these errors were encountered: