我如何将填充字符串的数组转换为JSON

发布于 2025-01-24 14:46:50 字数 227 浏览 2 评论 0原文

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)

我有一个错误:类型字节的对象不是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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱,才寂寞 2025-01-31 14:46:50

为什么在字符串之前键入“ B”?

您的代码尚未完成,我对其进行了修改以使其工作:

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)

如果您要当前的代码工作,如果要序列化数量的字符串,则必须使用'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)

Why you type 'b' before the strings ?

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:

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文