Skip to content

Instantly share code, notes, and snippets.

@mazzma12
Created November 28, 2023 16:35
Show Gist options
  • Save mazzma12/7b2c46145b1eb1fe97f1927dd43dd400 to your computer and use it in GitHub Desktop.
Save mazzma12/7b2c46145b1eb1fe97f1927dd43dd400 to your computer and use it in GitHub Desktop.
handy json serializer for numpy and pandas type
import numpy as np
import pandas as pd
def default_json_encoder(value):
# This should be built-in ...
if isinstance(value, (datetime.datetime, pd.Timestamp)):
return value.isoformat()
elif isinstance(value, np.bool_):
return bool(value)
elif isinstance(value, np.floating):
return float(value)
elif isinstance(value, np.integer):
return int(value)
elif isinstance(value, np.ndarray):
return value.tolist()
elif isinstance(value, set):
return list(value)
return value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment