git.net

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Bulletproof json.dump?


On Mon, Jul 6, 2020 at 11:06 PM Jon Ribbens via Python-list
<python-list at python.org> wrote:
>
> On 2020-07-06, Chris Angelico <rosuav at gmail.com> wrote:
> > On Mon, Jul 6, 2020 at 10:11 PM Jon Ribbens via Python-list
> ><python-list at python.org> wrote:
> >> While I agree entirely with your point, there is however perhaps room
> >> for a bit more helpfulness from the json module. There is no sensible
> >> reason I can think of that it refuses to serialize sets, for example.
> >
> > Sets don't exist in JSON. I think that's a sensible reason.
>
> It is not. Tuples don't exist either, and yet they're supported.

Hmm, I didn't know that. Possibly it's as much a bug as the inf/nan issue.

> >> Going a bit further and, for example, automatically calling isoformat()
> >> on date/time/datetime objects would perhaps be a bit more controversial,
> >> but would frequently be useful, and there's no obvious downside that
> >> occurs to me.
> >
> > They wouldn't round-trip without some way of knowing which strings
> > represent date/times.
>
> The 'json' module already fails to provide round-trip functionality:
>
>     >>> for data in ({True: 1}, {1: 2}, (1, 2)):
>     ...     if json.loads(json.dumps(data)) != data:
>     ...         print('oops', data, json.loads(json.dumps(data)))
>     ...
>     oops {True: 1} {'true': 1}
>     oops {1: 2} {'1': 2}
>     oops (1, 2) [1, 2]

There's a fundamental limitation of JSON in that it requires string
keys, so this is an obvious transformation. I suppose you could call
that one a bug too, but it's very useful and not too dangerous. (And
then there's the tuple-to-list transformation, which I think probably
shouldn't happen, although I don't think that's likely to cause issues
either.)

> > Maybe what people want is a pretty printer instead?
>
> No. I want a JSON encoder to output JSON to be read by a JSON decoder.

Does it need to round-trip, though? If you stringify your datetimes,
you can't decode it reliably any more. What's the purpose here?

ChrisA