python3中如何实现dict ndarray存成json并保留原数据精度

这篇文章主要介绍python3中如何实现dict ndarray存成json并保留原数据精度,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

如下所示:

import numpy as np
import codecs, json 
 
a = np.arange(10).reshape(2,5) # a 2 by 5 array
b = a.tolist() # nested lists with same data, indices
file_path = "/path.json" ## your path variable
json.dump(b, codecs.open(file_path, 'w', encoding='utf-8'), separators=(',', ':'), sort_keys=True, indent=4) ### this saves the array in .json format

关键是tolist和codecs编码,并转成适应json的格式。

解码并还原:

obj_text = codecs.open(file_path, 'r', encoding='utf-8').read()
b_new = json.loads(obj_text)
a_new = np.array(b_new)

以上是“python3中如何实现dict ndarray存成json并保留原数据精度”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注行业资讯频道!