How to deal with a single value when implementing jsonpickle custom handlers?
I wrote a custom handler for jsonpickle in order to transform an enum value before serializing the object container.
import jsonpickle
from enum import Enum
class Bar(Enum):
A = 1
B = 2
class Foo:
def __init__(self):
self.hello = 'hello'
self.bar = [Bar.A, Bar.B]
class Handler(jsonpickle.handlers.BaseHandler):
def flatten(self, obj, data): # data contains {}
print(obj)
### How should I handle the enum? ###
return data
jsonpickle.handlers.registry.register(Bar, Handler)
def main():
fizbuz = Foo()
encoded = jsonpickle.encode(fizbuz)
print(encoded)
if __name__ == '__main__':
main()
The handler is called with the obj containing the enum value all right. But then the data dict contains already a key, value pair so I can't just return a single value representing the enum.
So my question is what should be the key, value pair I need to add to the data dict when I am custom-handling elements that return one unique value while I need to fit it in the data dict that has been pre=-populated with reflection data that will be needed for the object to be reconstructed later.
python json python-3.x jsonpickle
add a comment |
I wrote a custom handler for jsonpickle in order to transform an enum value before serializing the object container.
import jsonpickle
from enum import Enum
class Bar(Enum):
A = 1
B = 2
class Foo:
def __init__(self):
self.hello = 'hello'
self.bar = [Bar.A, Bar.B]
class Handler(jsonpickle.handlers.BaseHandler):
def flatten(self, obj, data): # data contains {}
print(obj)
### How should I handle the enum? ###
return data
jsonpickle.handlers.registry.register(Bar, Handler)
def main():
fizbuz = Foo()
encoded = jsonpickle.encode(fizbuz)
print(encoded)
if __name__ == '__main__':
main()
The handler is called with the obj containing the enum value all right. But then the data dict contains already a key, value pair so I can't just return a single value representing the enum.
So my question is what should be the key, value pair I need to add to the data dict when I am custom-handling elements that return one unique value while I need to fit it in the data dict that has been pre=-populated with reflection data that will be needed for the object to be reconstructed later.
python json python-3.x jsonpickle
add a comment |
I wrote a custom handler for jsonpickle in order to transform an enum value before serializing the object container.
import jsonpickle
from enum import Enum
class Bar(Enum):
A = 1
B = 2
class Foo:
def __init__(self):
self.hello = 'hello'
self.bar = [Bar.A, Bar.B]
class Handler(jsonpickle.handlers.BaseHandler):
def flatten(self, obj, data): # data contains {}
print(obj)
### How should I handle the enum? ###
return data
jsonpickle.handlers.registry.register(Bar, Handler)
def main():
fizbuz = Foo()
encoded = jsonpickle.encode(fizbuz)
print(encoded)
if __name__ == '__main__':
main()
The handler is called with the obj containing the enum value all right. But then the data dict contains already a key, value pair so I can't just return a single value representing the enum.
So my question is what should be the key, value pair I need to add to the data dict when I am custom-handling elements that return one unique value while I need to fit it in the data dict that has been pre=-populated with reflection data that will be needed for the object to be reconstructed later.
python json python-3.x jsonpickle
I wrote a custom handler for jsonpickle in order to transform an enum value before serializing the object container.
import jsonpickle
from enum import Enum
class Bar(Enum):
A = 1
B = 2
class Foo:
def __init__(self):
self.hello = 'hello'
self.bar = [Bar.A, Bar.B]
class Handler(jsonpickle.handlers.BaseHandler):
def flatten(self, obj, data): # data contains {}
print(obj)
### How should I handle the enum? ###
return data
jsonpickle.handlers.registry.register(Bar, Handler)
def main():
fizbuz = Foo()
encoded = jsonpickle.encode(fizbuz)
print(encoded)
if __name__ == '__main__':
main()
The handler is called with the obj containing the enum value all right. But then the data dict contains already a key, value pair so I can't just return a single value representing the enum.
So my question is what should be the key, value pair I need to add to the data dict when I am custom-handling elements that return one unique value while I need to fit it in the data dict that has been pre=-populated with reflection data that will be needed for the object to be reconstructed later.
python json python-3.x jsonpickle
python json python-3.x jsonpickle
asked Apr 22 '18 at 6:47
LaurentLaurent
3,13712250
3,13712250
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
I don't understand why you're concerned about the dict that is supplied? That is an input for your use to aid in your handler code and doesn't need to be utilized at all if you don't want it. It isn't {}, as you indicated, if you use encode without unpicklable=False. If you don't include that, then you actually get this:
{'py/object': '__main__.Bar'}
All that is providing is the type of the variable and you wrote the handler, so you naturally know the type.
If you want a nice JSON output of your enum, just tell Python that obj of the flatten function is a Bar type (optional, but nice for the IDE and for later maintenance), like this:
def flatten(self, obj: Bar, data):
Then, just return obj.name. Doing this, the output is:
{"py/object": "__main__.Foo", "bar": ["A", "B"], "hello": "hello"}
Of course, we can make it cleaner by telling the encoder not to worry about decoding later with:
unpicklable=False
The final output is then:
{"bar": ["A", "B"], "hello": "hello"}
The whole example code:
import jsonpickle
from enum import Enum
class Bar(Enum):
A = 1
B = 2
class Foo:
def __init__(self):
self.hello = 'hello'
self.bar = [Bar.A, Bar.B]
class Handler(jsonpickle.handlers.BaseHandler):
def flatten(self, obj: Bar, data):
print(obj)
return obj.name
jsonpickle.handlers.registry.register(Bar, Handler)
def main():
fizbuz = Foo()
encoded = jsonpickle.encode(fizbuz, unpicklable=False)
print(encoded)
if __name__ == '__main__':
main()
Generic Approach
You can also generically handle all enums by using a class like this:
from enum import Enum
import jsonpickle
class JsonEnumHandler(jsonpickle.handlers.BaseHandler):
def restore(self, obj):
pass
def flatten(self, obj: Enum, data):
return obj.name
Then, register every enum in your JSON like this:
jsonpickle.handlers.registry.register(LimitType, JsonEnumHandler)
jsonpickle.handlers.registry.register(DeviceType, JsonEnumHandler)
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f49963305%2fhow-to-deal-with-a-single-value-when-implementing-jsonpickle-custom-handlers%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
I don't understand why you're concerned about the dict that is supplied? That is an input for your use to aid in your handler code and doesn't need to be utilized at all if you don't want it. It isn't {}, as you indicated, if you use encode without unpicklable=False. If you don't include that, then you actually get this:
{'py/object': '__main__.Bar'}
All that is providing is the type of the variable and you wrote the handler, so you naturally know the type.
If you want a nice JSON output of your enum, just tell Python that obj of the flatten function is a Bar type (optional, but nice for the IDE and for later maintenance), like this:
def flatten(self, obj: Bar, data):
Then, just return obj.name. Doing this, the output is:
{"py/object": "__main__.Foo", "bar": ["A", "B"], "hello": "hello"}
Of course, we can make it cleaner by telling the encoder not to worry about decoding later with:
unpicklable=False
The final output is then:
{"bar": ["A", "B"], "hello": "hello"}
The whole example code:
import jsonpickle
from enum import Enum
class Bar(Enum):
A = 1
B = 2
class Foo:
def __init__(self):
self.hello = 'hello'
self.bar = [Bar.A, Bar.B]
class Handler(jsonpickle.handlers.BaseHandler):
def flatten(self, obj: Bar, data):
print(obj)
return obj.name
jsonpickle.handlers.registry.register(Bar, Handler)
def main():
fizbuz = Foo()
encoded = jsonpickle.encode(fizbuz, unpicklable=False)
print(encoded)
if __name__ == '__main__':
main()
Generic Approach
You can also generically handle all enums by using a class like this:
from enum import Enum
import jsonpickle
class JsonEnumHandler(jsonpickle.handlers.BaseHandler):
def restore(self, obj):
pass
def flatten(self, obj: Enum, data):
return obj.name
Then, register every enum in your JSON like this:
jsonpickle.handlers.registry.register(LimitType, JsonEnumHandler)
jsonpickle.handlers.registry.register(DeviceType, JsonEnumHandler)
add a comment |
I don't understand why you're concerned about the dict that is supplied? That is an input for your use to aid in your handler code and doesn't need to be utilized at all if you don't want it. It isn't {}, as you indicated, if you use encode without unpicklable=False. If you don't include that, then you actually get this:
{'py/object': '__main__.Bar'}
All that is providing is the type of the variable and you wrote the handler, so you naturally know the type.
If you want a nice JSON output of your enum, just tell Python that obj of the flatten function is a Bar type (optional, but nice for the IDE and for later maintenance), like this:
def flatten(self, obj: Bar, data):
Then, just return obj.name. Doing this, the output is:
{"py/object": "__main__.Foo", "bar": ["A", "B"], "hello": "hello"}
Of course, we can make it cleaner by telling the encoder not to worry about decoding later with:
unpicklable=False
The final output is then:
{"bar": ["A", "B"], "hello": "hello"}
The whole example code:
import jsonpickle
from enum import Enum
class Bar(Enum):
A = 1
B = 2
class Foo:
def __init__(self):
self.hello = 'hello'
self.bar = [Bar.A, Bar.B]
class Handler(jsonpickle.handlers.BaseHandler):
def flatten(self, obj: Bar, data):
print(obj)
return obj.name
jsonpickle.handlers.registry.register(Bar, Handler)
def main():
fizbuz = Foo()
encoded = jsonpickle.encode(fizbuz, unpicklable=False)
print(encoded)
if __name__ == '__main__':
main()
Generic Approach
You can also generically handle all enums by using a class like this:
from enum import Enum
import jsonpickle
class JsonEnumHandler(jsonpickle.handlers.BaseHandler):
def restore(self, obj):
pass
def flatten(self, obj: Enum, data):
return obj.name
Then, register every enum in your JSON like this:
jsonpickle.handlers.registry.register(LimitType, JsonEnumHandler)
jsonpickle.handlers.registry.register(DeviceType, JsonEnumHandler)
add a comment |
I don't understand why you're concerned about the dict that is supplied? That is an input for your use to aid in your handler code and doesn't need to be utilized at all if you don't want it. It isn't {}, as you indicated, if you use encode without unpicklable=False. If you don't include that, then you actually get this:
{'py/object': '__main__.Bar'}
All that is providing is the type of the variable and you wrote the handler, so you naturally know the type.
If you want a nice JSON output of your enum, just tell Python that obj of the flatten function is a Bar type (optional, but nice for the IDE and for later maintenance), like this:
def flatten(self, obj: Bar, data):
Then, just return obj.name. Doing this, the output is:
{"py/object": "__main__.Foo", "bar": ["A", "B"], "hello": "hello"}
Of course, we can make it cleaner by telling the encoder not to worry about decoding later with:
unpicklable=False
The final output is then:
{"bar": ["A", "B"], "hello": "hello"}
The whole example code:
import jsonpickle
from enum import Enum
class Bar(Enum):
A = 1
B = 2
class Foo:
def __init__(self):
self.hello = 'hello'
self.bar = [Bar.A, Bar.B]
class Handler(jsonpickle.handlers.BaseHandler):
def flatten(self, obj: Bar, data):
print(obj)
return obj.name
jsonpickle.handlers.registry.register(Bar, Handler)
def main():
fizbuz = Foo()
encoded = jsonpickle.encode(fizbuz, unpicklable=False)
print(encoded)
if __name__ == '__main__':
main()
Generic Approach
You can also generically handle all enums by using a class like this:
from enum import Enum
import jsonpickle
class JsonEnumHandler(jsonpickle.handlers.BaseHandler):
def restore(self, obj):
pass
def flatten(self, obj: Enum, data):
return obj.name
Then, register every enum in your JSON like this:
jsonpickle.handlers.registry.register(LimitType, JsonEnumHandler)
jsonpickle.handlers.registry.register(DeviceType, JsonEnumHandler)
I don't understand why you're concerned about the dict that is supplied? That is an input for your use to aid in your handler code and doesn't need to be utilized at all if you don't want it. It isn't {}, as you indicated, if you use encode without unpicklable=False. If you don't include that, then you actually get this:
{'py/object': '__main__.Bar'}
All that is providing is the type of the variable and you wrote the handler, so you naturally know the type.
If you want a nice JSON output of your enum, just tell Python that obj of the flatten function is a Bar type (optional, but nice for the IDE and for later maintenance), like this:
def flatten(self, obj: Bar, data):
Then, just return obj.name. Doing this, the output is:
{"py/object": "__main__.Foo", "bar": ["A", "B"], "hello": "hello"}
Of course, we can make it cleaner by telling the encoder not to worry about decoding later with:
unpicklable=False
The final output is then:
{"bar": ["A", "B"], "hello": "hello"}
The whole example code:
import jsonpickle
from enum import Enum
class Bar(Enum):
A = 1
B = 2
class Foo:
def __init__(self):
self.hello = 'hello'
self.bar = [Bar.A, Bar.B]
class Handler(jsonpickle.handlers.BaseHandler):
def flatten(self, obj: Bar, data):
print(obj)
return obj.name
jsonpickle.handlers.registry.register(Bar, Handler)
def main():
fizbuz = Foo()
encoded = jsonpickle.encode(fizbuz, unpicklable=False)
print(encoded)
if __name__ == '__main__':
main()
Generic Approach
You can also generically handle all enums by using a class like this:
from enum import Enum
import jsonpickle
class JsonEnumHandler(jsonpickle.handlers.BaseHandler):
def restore(self, obj):
pass
def flatten(self, obj: Enum, data):
return obj.name
Then, register every enum in your JSON like this:
jsonpickle.handlers.registry.register(LimitType, JsonEnumHandler)
jsonpickle.handlers.registry.register(DeviceType, JsonEnumHandler)
edited Nov 14 '18 at 2:00
answered Nov 14 '18 at 1:52
Outfast SourceOutfast Source
1,18611015
1,18611015
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f49963305%2fhow-to-deal-with-a-single-value-when-implementing-jsonpickle-custom-handlers%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown