function clean_for_json_v1
Recursively traverses nested data structures (dicts, lists) and replaces NaN and Infinity float values with None to ensure JSON serialization compatibility.
/tf/active/vicechatdev/vice_ai/new_app.py
290 - 304
simple
Purpose
This utility function sanitizes Python data structures before JSON serialization by handling special float values (NaN, Infinity, -Infinity) that are not valid in JSON specification. It's commonly used when preparing data from numerical computations, pandas DataFrames, or scientific libraries for API responses or file storage in JSON format.
Source Code
def clean_for_json(obj):
"""
Recursively clean NaN and Infinity values from data structures.
Replaces them with None to ensure valid JSON output.
"""
import math
if isinstance(obj, dict):
return {k: clean_for_json(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [clean_for_json(item) for item in obj]
elif isinstance(obj, float):
if math.isnan(obj) or math.isinf(obj):
return None
return obj
return obj
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
obj |
- | - | positional_or_keyword |
Parameter Details
obj: Any Python object to be cleaned. Can be a primitive type (int, float, str, bool, None), a dictionary, a list, or nested combinations thereof. The function will recursively process nested structures to find and replace invalid float values.
Return Value
Returns a cleaned version of the input object with the same structure. All NaN and Infinity float values are replaced with None. Other data types and valid float values are preserved unchanged. Return type matches input type (dict returns dict, list returns list, etc.).
Dependencies
math
Required Imports
import math
Usage Example
import math
import json
def clean_for_json(obj):
import math
if isinstance(obj, dict):
return {k: clean_for_json(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [clean_for_json(item) for item in obj]
elif isinstance(obj, float):
if math.isnan(obj) or math.isinf(obj):
return None
return obj
return obj
# Example usage
data = {
'values': [1.5, float('nan'), 3.7, float('inf')],
'nested': {
'score': float('-inf'),
'valid': 42.0
},
'name': 'test'
}
cleaned_data = clean_for_json(data)
print(json.dumps(cleaned_data)) # Output: {"values": [1.5, null, 3.7, null], "nested": {"score": null, "valid": 42.0}, "name": "test"}
Best Practices
- Call this function on data structures before using json.dumps() or jsonify() when the data may contain NaN or Infinity values from numerical computations
- This function creates new objects rather than modifying in-place, so it's safe to use with shared data structures
- The function imports math internally, which is redundant if already imported at module level but ensures it works as a standalone function
- Consider using this when working with pandas DataFrames converted to dictionaries, as they often contain NaN values
- The function preserves the structure of nested data, making it safe for complex API responses
- Note that None is used as replacement, which serializes to null in JSON - ensure your API consumers can handle null values appropriately
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function clean_for_json_v11 92.4% similar
-
function clean_for_json_v4 91.7% similar
-
function clean_for_json_v6 91.0% similar
-
function clean_for_json_v2 90.0% similar
-
function clean_for_json_v5 88.8% similar