Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sending NaN in json

I am trying to encode an array which contains floats and NaN into JSON string from Python using json.dumps().

But the encoded JSON string is not being decoded successfully in PHP. Is the NaN causing this problem? How can I work around this situation?

like image 227
shreyas Avatar asked Jul 06 '11 19:07

shreyas


People also ask

Is NaN allowed in JSON?

NaN, Infinity and -Infinity are not part of JSON, but they are standard in Javascript, so they're commonly used extensions. If the recipient can't handle them, set allow_nan=False . But then you'll get ValueError when you try to serialise NaN.

How are numeric values like infinity and NaN handled in JSON?

How does JSON handle numeric values that cannot be represented by a sequence of digits (like Infiniti and Nan)? They are not permitted. They are stored as strings and then converted when parsed. They are stored fine but it's the parsers job to convert them to numeric values.

Is undefined valid JSON?

Undefined is not a valid JSON type. All javascript objects are not valid JSON and vice versa. All other values will be sent to the response but undefined won't be sent.

What is none in JSON?

There is no NULL in Python. Instead, it has None. JSON has a NULL data type, but it has not a None data type. A dictionary in Python cannot have null as a value but can have “null” as a value that can be interpreted as a string.


1 Answers

json.dumps has an allow_nan parameter, which defaults to True.

NaN, Infinity and -Infinity are not part of JSON, but they are standard in Javascript, so they're commonly used extensions. If the recipient can't handle them, set allow_nan=False. But then you'll get ValueError when you try to serialise NaN.

like image 140
Thomas K Avatar answered Sep 23 '22 03:09

Thomas K