我想序列化一个填充了复数的ndarray / list,示例代码在这里:
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
那么如何处理这个问题呢?
答案 0 :(得分:0)
json.dumps(a)
将失败,因为该函数在尝试解释时无法处理复数。传递该值的唯一可能是字符串:
a = [1]
a[0] = "0.006863076166054825+0j"
b = json.dumps(a)
print b
输出
["0.006863076166054825+0j"]
答案 1 :(得分:0)
好吧,让我说清楚
我找到了另一种方法。 使用模块pickle
例如:
fp = open("1.txt","w")
a = [1,2,3]
pickle.dump(a,fp,0)
fp.close()
加载是一样的:
fp = open("1.txt")
a = pickle.load(fp)
print a
fp.close()
它可以序列化任何对象,只要它可以找到类
答案 2 :(得分:0)
我也需要这个问题的解决方案。我已经编写了这段代码,它可以满足我所需的任务,但是当我通过检查运行它时,并不能完成所有任务。仍然可以使用它。
# turn complex to str
def replace_complex( inp):
"""Replace complex numbers with strings of
complex number + __ in the beginning.
Parameters:
------------
inp: input dictionary.
"""
try:
if isinstance(inp, complex):
return "__" + str(inp)
elif isinstance(inp, list):
for each in range(len(inp)):
inp[ each] = replace_complex( inp[ each])
return inp
elif isinstance(inp, dict):
for key,val in inp.items():
inp[key] = replace_complex( val)
return inp
else:
return inp # nothing found - better than no checks
except Exception as e:
print(e)
return ""