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

Bulletproof json.dump?

On 2020-07-06, Chris Angelico <rosuav at> wrote:
> On Tue, Jul 7, 2020 at 12:01 AM Jon Ribbens via Python-list
><python-list at> wrote:
>> 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.)

Yes, I agree (although you'd need to call it something other than
'strict' mode, since that flag already exists). But note nothing
I am suggesting would involve JSONEncoder ever producing non-standard
output (except in cases where it already would).