I have a nested dictionary that I am trying to convert to JSON using json.dumps(unserialized_data), indent=2)
. The dictionary currently looks like this:
{
"status": "SUCCESS",
"data": {
"cal": [
{
"year": 2022,
"month": 8,
"a": [
{
"a_id": 1,
"b": [
{
"abc_id": 1,
"val": 2342
}
]
}
]
},
{
"year": 2022,
"month": 9,
"a": [
{
"a_id": 2,
"b": [
{
"abc_id": 3,
"val": 2342
}
]
}
]
}
]
}
}
How can I convert all integers of type int64
to int
while leaving the structure of the dict and values of any other data type unaffected?
2
Answers
If the only objects in your dict that aren’t JSON-serializable are all of type
int64
, you can easily serialize them by makingint
the default function for converting objects that JSON can’t serialize:If blhsing’s condition doesn’t apply, you can drill down recursively into the dictionary and cast any
np.int64
toint
:from_types
andto_types
are containers where corresponding elements give the type to convert from, and the type to convert to.Run your dictionary through this function, then dump it to json:
Prints the dictionary as JSON:
Try online