1

Hi I have a following code:

def dah(o):
    assert False
print simplejson.dumps(['string', None, 3, 0], default=dah)

The problem is that the code above should throw an exception - but it does not. It completely ignores my default class.

I have also tried to use this:

class NoneToEmptyStringEncoder(simplejson.JSONEncoder):
    """
    Json encoder that replaces nulls with empty strings
    """
    def default(self, o):
        assert False
        if o:
            return super(NoneToEmptyStringEncoder, self).default(o)
        else:
            return super(NoneToEmptyStringEncoder, self).default('')
print simplejson.dumps(['string', None, 3, 0], cls=NoneToEmptyStringEncoder)

But again it does not throw AssertionError, it completely ignores my doing and works normally.

Am I missing here something?

Visgean Skeloru
  • 2,237
  • 1
  • 24
  • 33
  • 3
    Why do you expect `dah` to be called in the first example? Everything there (list, string, `None` and integers) are things `simplejson` knows about. `default` is called only for object types it *doesn't* know about. (BTW, `None` is translated to `null`). – Tim Peters Nov 02 '13 at 03:21
  • 1
    See http://docs.python.org/2/library/json.html#py-to-json-table. – Warren Weckesser Nov 02 '13 at 03:30
  • @WarrenWeckesser, that's generally helpful, but the OP isn't using Python's `json` modules - they're using [`simplejson`](https://pypi.python.org/pypi/simplejson/). Differences should be minimal at worst, though :-) – Tim Peters Nov 02 '13 at 03:33
  • 1
    @TimPeters: True, but http://stackoverflow.com/questions/712791/what-are-the-differences-between-json-and-simplejson-python-modules. Still, for completeness: http://simplejson.readthedocs.org/en/latest/#encoders-and-decoders – Warren Weckesser Nov 02 '13 at 03:38
  • @TimPeters Oh, that explains a lot, I thought that this will be used everytime, not just new types. I will have to override different method than. – Visgean Skeloru Nov 02 '13 at 13:52

0 Answers0