function clean_for_json_v13
Recursively sanitizes Python objects to make them JSON-serializable by converting NumPy types to native Python types and handling NaN/Inf values.
/tf/active/vicechatdev/vice_ai/smartstat_scripts/d48d7789-9627-4e96-9f48-f90b687cd07d/analysis_1.py
356 - 371
simple
Purpose
This function prepares data structures containing NumPy arrays, pandas data types, or special float values (NaN, Inf) for JSON serialization. It recursively traverses dictionaries and lists, converting NumPy integers to Python ints, NumPy floats to Python floats, and replacing NaN/Inf values with None. This is essential when working with scientific computing libraries and needing to export data to JSON format.
Source Code
def clean_for_json(obj):
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
elif isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
if math.isnan(obj) or math.isinf(obj):
return None
return float(obj)
return obj
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
obj |
- | - | positional_or_keyword |
Parameter Details
obj: Any Python object to be cleaned for JSON serialization. Can be a dict, list, float, NumPy integer, NumPy floating point number, or any other type. Nested structures (dicts containing lists, lists containing dicts, etc.) are supported and will be recursively processed.
Return Value
Returns a JSON-serializable version of the input object. Dictionaries return dictionaries with cleaned values, lists return lists with cleaned elements, NumPy integers return Python ints, NumPy floats return Python floats (or None if NaN/Inf), regular floats return themselves (or None if NaN/Inf), and all other types are returned unchanged. The structure of nested objects is preserved.
Dependencies
numpymath
Required Imports
import numpy as np
import math
Usage Example
import numpy as np
import math
def clean_for_json(obj):
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
elif isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
if math.isnan(obj) or math.isinf(obj):
return None
return float(obj)
return obj
# Example usage
data = {
'values': [np.int64(42), np.float64(3.14), float('nan'), float('inf')],
'nested': {
'numpy_val': np.float32(2.718),
'regular': 100
}
}
cleaned = clean_for_json(data)
print(cleaned)
# Output: {'values': [42, 3.14, None, None], 'nested': {'numpy_val': 2.718, 'regular': 100}}
import json
json_string = json.dumps(cleaned)
print(json_string)
Best Practices
- Use this function before calling json.dumps() on data structures that may contain NumPy types or NaN/Inf values
- Be aware that NaN and Inf values are converted to None, which may affect downstream processing that expects numeric values
- This function does not handle all possible NumPy types (e.g., datetime64, complex numbers) - only integers and floating point numbers
- For large nested structures, consider the performance implications of recursive processing
- The function preserves the original structure but creates new objects, so it does not modify the input in-place
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function clean_for_json_v15 96.5% similar
-
function clean_for_json_v14 95.7% similar
-
function clean_for_json_v12 95.2% similar
-
function clean_for_json_v11 94.0% similar
-
function clean_for_json_v3 93.5% similar