当前位置:首页 » python教程 » 正文

python3 dict ndarray 存成json,并保留原数据精度的实例

看: 738次  时间:2021-01-22  分类 : python教程

如下所示:

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)

转自:https://stackoverflow.com/questions/26646362/numpy-array-is-not-json-serializable

以上这篇python3 dict ndarray 存成json,并保留原数据精度的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持python博客。

标签:numpy  

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!