1

I have a class object that I am serializing with json. The following code serializes the class and it works fine if there are no ndarray members. But if I include ndarray in class I get error as ndarry requires to be converted to list for serialization as mentioned here.

I have a class as follows:

class foo_datastructure():
  def __init__(self):
    self.a=0
    self.b=0
    self.c=[]
    self.array_dictinary= {}
   

The list and variables work fine but the dictionary part gives ndarray issue. The dictionary is of the following type:

self.array_dict[key]={'x':[],'y':[],'z':[]}

Now I want to retain my code as follows to convert the class:

 def toJSON(self):

    return json.dumps(self, default=lambda o: o.__dict__,
                      sort_keys=True, indent=4)

and decode it as:

received = (json.loads(Obj, object_hook=lambda d: namedtuple('X', d.keys())(*d.values())))

how can i change default=lambda o: o.__dict__ so it also accounts for the dictionary with array?

user0193
  • 288
  • 1
  • 7
  • 1
    Does this answer your question? [Json Encoder AND Decoder for complex numpy arrays](https://stackoverflow.com/questions/27909658/json-encoder-and-decoder-for-complex-numpy-arrays) – Corralien Jun 27 '21 at 20:25
  • @Corralien thanks, I am aware of the solution however I am trying to change the lambda function, that accounts for ndarray. Using the link, I will also have to modify the loading code – user0193 Jun 27 '21 at 20:32

0 Answers0