Skip to content

Instantly share code, notes, and snippets.

@RonjaPonja
Created July 17, 2019 10:08
Show Gist options
  • Select an option

  • Save RonjaPonja/404b0b5588acbb670dc74cdc24f2b41d to your computer and use it in GitHub Desktop.

Select an option

Save RonjaPonja/404b0b5588acbb670dc74cdc24f2b41d to your computer and use it in GitHub Desktop.
In [7]: zz={1:2, '1':'2'}
In [8]: zz
Out[8]: {1: 2, '1': '2'}
In [9]: json.dumps(zz)
Out[9]: '{"1": 2, "1": "2"}'
In [11]: qq=json.loads(json.dumps(zz))
In [12]: qq
Out[12]: {'1': '2'}
@cyber-murmel
Copy link
Copy Markdown

yeah, but json can't have non-string keys. so that's perfectly normal and should be considered while coding...

@RonjaPonja
Copy link
Copy Markdown
Author

you are technically correct, the best kind of correct

I understand the limitations of JSON perfectly well, yet I think:

  • Dumps should never output JSON with duplicate keys. That's a non starter, some parsers will not even parse this. Even the RFC says The names within an object SHOULD be unique. https://tools.ietf.org/html/rfc7159#section-4
  • IMO dumps should not try to str(key). I could maybe accept their eagerness for convenience here if my dict key is some random object and not a basic data type. Even then this should probably be explicitly enabled via a keyword argument of dumps.
  • Here is where it gets really strange though. If you try to dump a dict with a key which is an instance of a custom class implementing __str__ you will get.. TypeError: keys must be a string. So it does the exact opposite. kthx
  • the loads situation is more tricky. Following Postel's law it just might be okay to let the duplicate key slide, but it's still somewhat dangerous. I would at least expect something like a RuntimeWarning here.

Telling people to write their complex software carefully is about as sane as telling them to drive their tank carefully. This stuff is complicated.

@cyber-murmel
Copy link
Copy Markdown

Yeah, an exception would be appropriate when doing json.dumps(zz)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment