Skip to content
Advertisement

How to convert nested numpy arrays in a dictionary to JSON?

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

I will get the following error:

JavaScript

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

Prints:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement