Python JSON encoder convert NaNs to null instead

Python JSON encoder convert NaNs to null instead

In Python's json module, NaN (Not a Number) values are not natively supported for JSON serialization. By default, trying to serialize NaN values using json.dumps() will raise a ValueError. However, you can work around this by creating a custom JSON encoder that converts NaN values to null.

Here's an example of how you could achieve this:

import json import math class CustomJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, float) and math.isnan(obj): return None return super().default(obj) # Create some data with NaN values data = { "value1": 42, "value2": float('nan'), "value3": [1.0, 2.0, float('nan')], } # Serialize using the custom encoder json_string = json.dumps(data, cls=CustomJSONEncoder) print(json_string) 

In this example, the CustomJSONEncoder class extends json.JSONEncoder and overrides the default method to handle NaN values by converting them to None. When you use this custom encoder with json.dumps(), NaN values in your data will be serialized as null in the resulting JSON string.

Please note that using None to represent NaN values is a common workaround, but it's not a perfect solution as None can have different interpretations in various contexts. Make sure that the consumer of your JSON data understands this conversion.

Examples

  1. "Python JSON encoder convert NaNs to null instead"

    • Description: This query likely arises from developers seeking a solution to handle NaN values in Python and convert them to null when encoding JSON.
    import json def nan_to_null(obj): if isinstance(obj, float) and obj != obj: return None elif isinstance(obj, dict): return {k: nan_to_null(v) for k, v in obj.items()} elif isinstance(obj, list): return [nan_to_null(item) for item in obj] else: return obj data = {"value": float('nan')} encoded_json = json.dumps(nan_to_null(data)) print(encoded_json) 
  2. "Python handle NaN in JSON serialization"

    • Description: Developers may be looking for methods to properly handle NaN values during JSON serialization in Python.
    import json def handle_nan(obj): if isinstance(obj, float) and obj != obj: return None raise TypeError(f'Object of type {type(obj)} is not JSON serializable') data = {"value": float('nan')} encoded_json = json.dumps(data, default=handle_nan) print(encoded_json) 
  3. "Python JSON encode NaN as null"

    • Description: This query indicates a desire to find a straightforward way to ensure NaN values are represented as null in JSON encoding.
    import json def nan_to_null(obj): if isinstance(obj, float) and obj != obj: return None return obj data = {"value": float('nan')} encoded_json = json.dumps(data, default=nan_to_null) print(encoded_json) 
  4. "Convert NaN to null in Python JSON serialization"

    • Description: Developers may seek a solution to convert NaN values to null during JSON serialization in Python.
    import json def nan_to_null(obj): if isinstance(obj, float) and obj != obj: return None return obj data = {"value": float('nan')} encoded_json = json.dumps(data, default=nan_to_null) print(encoded_json) 
  5. "Python JSON encoder convert NaN to null"

    • Description: This query suggests a need for a JSON encoder in Python that automatically converts NaN values to null.
    import json class CustomJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, float) and obj != obj: return None return super().default(obj) data = {"value": float('nan')} encoded_json = json.dumps(data, cls=CustomJSONEncoder) print(encoded_json) 
  6. "Python NaN to null JSON encoding"

    • Description: Developers might be specifically looking for a concise method to encode NaN values as null in JSON using Python.
    import json data = {"value": float('nan')} encoded_json = json.dumps(data, default=lambda x: None if isinstance(x, float) and x != x else x) print(encoded_json) 
  7. "Handle NaN in Python JSON encoding"

    • Description: This query indicates a need to handle NaN values during JSON encoding in Python.
    import json def nan_handler(x): if isinstance(x, float) and x != x: return None raise TypeError(f'Object of type {type(x)} is not JSON serializable') data = {"value": float('nan')} encoded_json = json.dumps(data, default=nan_handler) print(encoded_json) 
  8. "Python JSON NaN to null conversion"

    • Description: Developers might be seeking a way to convert NaN values to null during JSON serialization in Python.
    import json def nan_to_null(obj): if isinstance(obj, float) and obj != obj: return None return obj data = {"value": float('nan')} encoded_json = json.dumps(data, default=nan_to_null) print(encoded_json) 
  9. "JSON encoding Python handle NaN values"

    • Description: This query suggests a need to handle NaN values specifically during JSON encoding in Python.
    import json def nan_handler(x): if isinstance(x, float) and x != x: return None raise TypeError(f'Object of type {type(x)} is not JSON serializable') data = {"value": float('nan')} encoded_json = json.dumps(data, default=nan_handler) print(encoded_json) 
  10. "Python JSON encoder convert NaN to null solution"

    • Description: Developers may be seeking a definitive solution to ensure NaN values are converted to null during JSON encoding in Python.
    import json def nan_to_null(obj): if isinstance(obj, float) and obj != obj: return None return obj data = {"value": float('nan')} encoded_json = json.dumps(data, default=nan_to_null) print(encoded_json) 

More Tags

material-ui pickle flutter-appbar django-widget file-rename subscription hidden-files tampermonkey timedelta slider

More Python Questions

More Gardening and crops Calculators

More Biochemistry Calculators

More Entertainment Anecdotes Calculators

More Everyday Utility Calculators