-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Override JSONEncoder.iterencode
#203
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
We do this to handle NaN, Inf, and -Inf
@chriddyp , this one looked like a quickie, so I just grabbed it. |
# we want stricter JSON, so convert NaN, Inf, -Inf --> 'null' | ||
nan_str = inf_str = neg_inf_str = 'null' | ||
|
||
# uses code from official python json.encoder module. Same licence applies. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
woah gnarly
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this may be naive, but can't we just extend our current encoder with a check for is NaN
, Inf
? like how we do with datetimes https://github.com/plotly/python-api/blob/master/plotly/utils.py#L224
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
situation kinda stinks, I actually documented it because this same thing was confusing to me as well:
https://github.com/plotly/python-api/blob/master/plotly/utils.py#L135-150
We only get a crack at stuff if the JSONEncoder can't encode it. What's more, as is mentioned in the SO post, when allow_nan=False
, we also don't get a crack at it in our encoder. bummer!
Here's an example:
import json
import numpy
class Foo(object):
pass
class NullEncoder(json.JSONEncoder):
def encode_as_true(self, obj):
return None
def default(self, obj):
return self.encode_as_true(obj)
json.dumps(Foo(), cls=NullEncoder) # here, it works
# 'null'
json.dumps(numpy.ma.core.masked, cls=NullEncoder) # and again here
# 'null'
json.dumps(float('NaN'), cls=NullEncoder) # no shot! this doesn't work as expected!
# 'NaN'
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
wow, that's pretty wild. well, that looks good then, nice diggin!
Python uses extended JSON which allows for NaN, Infinity, -Infinity. This means that a `JSON.parse()` on one of our encoded JSON strings will fail. This is no longer the case.
@chriddyp , i'm ready to roll this out when tests pass. nice catch on this! |
boom! Sent from my iPhone
|
Override `JSONEncoder.iterencode`
We do this to handle NaN, Inf, and -Inf
Fixes: #202
Todo: