Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to serialize an array/list/mat filled with complex number

I want to serialize an ndarray/list filled with complex number, the example code is here:

a = [None]
a[0] =  0.006863076166054825+0j
a
[(0.006863076166054825+0j)]
>>> b = json.dumps(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\Python27\lib\json\__init__.py", line 243, in dumps
    return _default_encoder.encode(obj)
  File "D:\Python27\lib\json\encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "D:\Python27\lib\json\encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
  File "D:\Python27\lib\json\encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: (0.006863076166054825+0j) is not JSON serializable

so how to deal with the problem?

like image 283
ruiruige1991 Avatar asked Feb 03 '26 19:02

ruiruige1991


1 Answers

The json.dumps(a) will fail, because the function can not handle the complex number when it tries to interpret it. The only possibility to pass the value is as string:

a = [1]
a[0] = "0.006863076166054825+0j"
b = json.dumps(a)
print b

which outputs

["0.006863076166054825+0j"]
like image 54
hexerei software Avatar answered Feb 06 '26 10:02

hexerei software