Created
November 30, 2015 15:54
-
-
Save josefdlange/65c9c3ead9d42699fd8b to your computer and use it in GitHub Desktop.
Implementing custom JSON logic for the Python json module.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import json | |
| from json import JSONEncoder | |
| class MyComplexObject(object): | |
| """ | |
| A trivial Python object that has its own special serialized output | |
| that for some reason would differ from __repr__. | |
| """ | |
| def __init__(self, arbitrary_value, optional_value=None): | |
| self.arbitrary_value = arbitrary_value | |
| self.optional_value = optional_value | |
| def prepared(self): | |
| if self.optional_value: | |
| return "{0} ({1})".format(self.arbitrary_value, self.optional_value) | |
| else: | |
| return self.arbitrary_value | |
| class MyEncoder(JSONEncoder): | |
| def default(self, o): | |
| if isinstance(o, MyComplexObject): | |
| return o.prepared() | |
| return JSONEncoder.default(self, o) | |
| complex_object = MyComplexObject('foo', optional_value='bar') | |
| data = { | |
| 'object': complex_object, | |
| 'number': 2, | |
| 'metadata': { | |
| 'is_hungry': True, | |
| 'banana_count': 0 | |
| } | |
| } | |
| output = json.dumps(data, cls=MyEncoder) | |
| expected = '{"object": "foo (bar)", "number": 2, "metadata": {"is_hungry": true, "banana_count": 0}}' | |
| assert output == expected |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment