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

Bulletproof json.dump?

On Tue, Jul 7, 2020 at 12:01 AM Jon Ribbens via Python-list
<python-list at> wrote:
> On 2020-07-06, Chris Angelico <rosuav at> wrote:
> > I think that even in non-strict mode, round-tripping should be
> > achieved after one iteration. That is to say, anything you can
> > JSON-encode will JSON-decode to something that would create the same
> > encoded form. Not sure if there's anything that would violate that
> > (weak) guarantee.
> I think what you're saying is, if we do:
>     json1 = json.dumps(foo)
>     json2 = json.dumps(json.loads(json1))
>     assert json1 == json2
> the assertion should never fail (given that Python dictionaries are
> ordered these days). I seems to me that should probably be true
> regardless of any 'strict mode' flag - I can't immediately think of
> any reason it wouldn't be.

Right. But in strict mode, the stronger assertion would hold:

assert obj == json.loads(json.dumps(obj))

Also, the intermediate text would be RFC-compliant. If this cannot be
done, ValueError would be raised. (Or maybe TypeError in some cases.)