I’m parsing nested dictionaries, which have different degrees of how nested they are (dictionaries within dictionaries within dictionaries, etc.) I do not know beforehand to what degree the dictionaries are nested.
The problem is, certain dictionary values are numpy.ndarrays
. When I try to write the dictionary my_dictionary
to JSON with
JavaScript
x
3
1
with open(my_dictionary, 'w') as f:
2
json.dump(my_dictionary, f, indent=4)
3
I will get the following error:
JavaScript
1
2
1
TypeError: Object of type ndarray is not JSON serializable
2
Naturally, one way to overcome this would be to simply convert all numpy.ndarray
values into a list with .tolist()
.
However, given I do not know how nested the dictionaries are, how could I algorithmically check all values of any nested dictionary and convert ndarray
to list?
Or is there another way to overcome this error?
Advertisement
Answer
You can make custom json.JSONEncoder
. For example:
JavaScript
1
14
14
1
import json
2
3
4
class MyEncoder(json.JSONEncoder):
5
def default(self, obj):
6
if isinstance(obj, np.ndarray):
7
return obj.tolist()
8
return json.JSONEncoder.default(self, obj)
9
10
11
data = {"data": [{"obj": np.array([1, 2, 3])}]}
12
13
print(json.dumps(data, cls=MyEncoder, indent=4))
14
Prints:
JavaScript
1
12
12
1
{
2
"data": [
3
{
4
"obj": [
5
1,
6
2,
7
3
8
]
9
}
10
]
11
}
12