[英]How do I convert a numpy array filled with strings to json
n=int(input('n='))
array = np.empty(shape=
[n,4],dtype='|S10')
.
.
.
.
array= array.tolist()
array =[[b'1',b'1/1/1',b'1',b'1']]
dump(array,json_file)
I got an error: Object of type bytes is not JSON serializable我得到一个错误:字节类型的 Object 不是 JSON 可序列化的
Why you type 'b' before the strings?为什么在字符串前输入“b”?
Your code is not complete, I modified it to let it work:你的代码不完整,我修改了它让它工作:
import numpy as np
import json
n=int(input('n='))
array = np.empty(shape=[n,4],dtype='|S10')
array = [['1', '1/1/1', '1', '1']]
with open('test.json', 'w') as json_file:
json.dump(array, json_file)
That if you want your current code to work, if you want to serialize a numpy array of strings you must use 'U1' dtype and then convert it to list, like this:如果你想让你当前的代码工作,如果你想序列化一个 numpy 字符串数组,你必须使用 'U1' dtype 然后将它转换为列表,如下所示:
import numpy as np
import json
n = int(input('n='))
array = np.empty(shape=[n,4], dtype='U1')
array = array.tolist()
with open('test.json', 'w') as json_file:
json.dump(array, json_file)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.