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

Bulletproof json.dump?

On 2020-07-06, Adam Funk wrote:

> On 2020-07-06, Chris Angelico wrote:
>> On Mon, Jul 6, 2020 at 10:11 PM Jon Ribbens via Python-list
>><python-list at> 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.
> I don't agree.  Tuples & lists don't exist separately in JSON, but
> both are serializable (to the same thing).  Non-string keys aren't
> allowed in JSON, but it silently converts numbers to strings instead
> of barfing.  Typically, I've been using sets to deduplicate values as
> I go along, & having to walk through the whole object changing them to
> lists before serialization strikes me as the kind of pointless labor
> that I expect when I'm using Java.  ;-)

Here's another "I'd expect to have to deal with this sort of thing in
Java" example I just ran into:

>>> r = requests.head(url, allow_redirects=True)
>>> print(json.dumps(r.headers, indent=2))
TypeError: Object of type CaseInsensitiveDict is not JSON serializable
>>> print(json.dumps(dict(r.headers), indent=2))
  "Content-Type": "text/html; charset=utf-8",
  "Server": "openresty",

I'm after rebellion --- I'll settle for lies.