Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python JSON encoder convert NaNs to null instead

I'm writing code to receive an arbitrary object (possibly nested) capable of being converted to JSON.

The default behavior for Python's builtin JSON encoder is to convert NaNs to NaN, e.g. json.dumps(np.NaN) results in NaN. How can I change this NaN value to null?

I tried to subclass JSONEncoder and override the default() method as follows:

from json import JSONEncoder, dumps import numpy as np      class NanConverter(JSONEncoder):     def default(self, obj):         try:             _ = iter(obj)         except TypeError:             if isinstance(obj, float) and np.isnan(obj):                 return "null"         return JSONEncoder.default(self, obj)  >>> d = {'a': 1, 'b': 2, 'c': 3, 'e': np.nan, 'f': [1, np.nan, 3]} >>> dumps(d, cls=NanConverter) '{"a": 1, "c": 3, "b": 2, "e": NaN, "f": [1, NaN, 3]}' 

EXPECTED RESULT: '{"a": 1, "c": 3, "b": 2, "e": null, "f": [1, null, 3]}'

like image 829
Alexander Avatar asked Feb 20 '15 23:02

Alexander


People also ask

Does JSON accept NaN?

NaN isn't valid JSON (https://tools.ietf.org/html/rfc8259 sec 6) and should probably be changed to null.

What is JSON dump?

The json. dumps() method allows us to convert a python object into an equivalent JSON object. Or in other words to send the data from python to json. The json. dump() method allows us to convert a python object into an equivalent JSON object and store the result into a JSON file at the working directory.

What is FP in JSON dump?

A fp is a file pointer used to write JSON formatted data into file. Python json module always produces string objects, not bytes objects, therefore, fp.

What is JSON dumps and loads?

json loads -> returns an object from a string representing a json object. json dumps -> returns a string representing a json object from an object. load and dump -> read/write from/to file instead of string.


1 Answers

This seems to achieve my objective:

import simplejson   >>> simplejson.dumps(d, ignore_nan=True) Out[3]: '{"a": 1, "c": 3, "b": 2, "e": null, "f": [1, null, 3]}' 
like image 176
Alexander Avatar answered Oct 04 '22 02:10

Alexander