简体   繁体   English

如何将充满字符串的 numpy 数组转换为 json

[英]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.

相关问题 如何将 dataframe 中填满数字的列转换为 python 中的字符串? - How do I convert a dataframe column filled with numbers to strings in python? 如何将 numpy 数组转换为 gif? - How do I convert a numpy array to a gif? 如何将字符串数组转换为 numpy 中的浮点数数组? - How to convert an array of strings to an array of floats in numpy? 如何同时加载字符串和浮点数到numpy数组中? - How do I load both Strings and floats into a numpy array? 如何使用 Numpy 对字符串数组进行一次热编码? - How do I one-hot encode an array of strings with Numpy? 如何将字符串列表转换为数字numpy数组? - How to convert a list of strings into a numeric numpy array? 如何将字符串列表转换为数组? (不使用 NumPy) - How to convert a list of strings to an array? (NOT using NumPy) 如何将字符串的numpy数组转换为集合的numpy数组以使用MultiLabelBinarizer? - How to convert a numpy array of strings to a numpy array of sets to use MultiLabelBinarizer? 如何将2D numpy数组转换为1D numpy数组的1D numpy数组? - How do I convert a 2D numpy array into a 1D numpy array of 1D numpy arrays? 如何将多个带有整数的 NumPy arrays 转换为带有格式化字符串的 NumPy 数组? - How can I convert several NumPy arrays with ints to a NumPy array with formatted strings?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM