constantly icon indicating copy to clipboard operation
constantly copied to clipboard

ValueConstants are not JSON serializable

Open jml opened this issue 10 years ago • 1 comments

In [1]: from constantly import Values, ValueConstant

In [2]: class Foo(Values):
   ...:     foo = ValueConstant('foo')
   ...:     bar = ValueConstant('bar')
   ...:

In [3]: import json

In [4]: json.dumps([Foo.foo, Foo.bar])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-5375b22f7626> in <module>()
----> 1 json.dumps([Foo.foo, Foo.bar])

/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.pyc in dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, encoding, default, sort_keys, **kw)
    241         cls is None and indent is None and separators is None and
    242         encoding == 'utf-8' and default is None and not sort_keys and not kw):
--> 243         return _default_encoder.encode(obj)
    244     if cls is None:
    245         cls = JSONEncoder

/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.pyc in encode(self, o)
    205         # exceptions aren't as detailed.  The list call should be roughly
    206         # equivalent to the PySequence_Fast that ''.join() would do.
--> 207         chunks = self.iterencode(o, _one_shot=True)
    208         if not isinstance(chunks, (list, tuple)):
    209             chunks = list(chunks)

/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.pyc in iterencode(self, o, _one_shot)
    268                 self.key_separator, self.item_separator, self.sort_keys,
    269                 self.skipkeys, _one_shot)
--> 270         return _iterencode(o, 0)
    271
    272 def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,

/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.pyc in default(self, o)
    182
    183         """
--> 184         raise TypeError(repr(o) + " is not JSON serializable")
    185
    186     def encode(self, o):

TypeError: <Foo=foo> is not JSON serializable

I would expect Foo.foo to serialize to "foo", Foo.bar to serialize to "bar". In general, for a ValueConstant to serialize to whatever its value serializes to.

jml avatar Aug 12 '15 12:08 jml

I don't think the batteries-included json module supports this. This answer supports my hunch. You'd need to provide a custom serializer, json.dumps(.., cls=..). That's not something that the ValueConstants class can do; it's something that must be done everywhere json.dumps is called.

djmitche avatar Feb 17 '17 02:02 djmitche