0

I must convert a list (whose elements are arrays) into list. When printed its content is as follows:

[
array([[100.1, 120.4, 156.4, 458.5, 0.99]], dtype=float32), 
array([[120.3, 168.9, 169.3, 770.2, 0.89]], dtype=float32), 
array([[850.1, 671.5, 222.1, 563.4, 0.88]], dtype=float32)
]

What I need is some list which is json serializable. Because when I use json.dump, it's returning:

TypeError: Object of type ndarray is not JSON serializable

I know that it is still list but with arrays as its elements. How do I convert it properly?

bit_scientist
  • 1,496
  • 2
  • 15
  • 34
  • https://stackoverflow.com/questions/26646362/numpy-array-is-not-json-serializable – Dani Mesejo Oct 01 '21 at 09:43
  • 1
    Does this answer your question? [NumPy array is not JSON serializable](https://stackoverflow.com/questions/26646362/numpy-array-is-not-json-serializable) – Jonathan1609 Oct 01 '21 at 09:43

1 Answers1

0

json.dump does not work on NumPy arrays as pointed out by @Dani and @Jonathan1609.

To use json.dump you have to covert all the arrays to python lists and then call json.dump.

l = [
array([[100.1, 120.4, 156.4, 458.5, 0.99]], dtype=float32), 
array([[120.3, 168.9, 169.3, 770.2, 0.89]], dtype=float32), 
array([[850.1, 671.5, 222.1, 563.4, 0.88]], dtype=float32)
]
l = [i.tolist() for in l]
json.dump(l)

or you can write your own Serializer if you don't want to change the datatype.

import json
import numpy as np

class NumpyEncoder(json.JSONEncoder):
    """ Special json encoder for numpy types """
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        return json.JSONEncoder.default(self, obj)

dumped = json.dump(l, cls=NumpyEncoder)
kinshukdua
  • 1,944
  • 1
  • 5
  • 15