我的代码将读取CSV文件并将其转换为JSON中的对象数组。然而,我需要的是一个多维数组(即数组数组)
以下是我的python代码:
import pandas
import json
df = pandas.read_csv('test.json', names=("en","th"))
df.to_json('test.json', orient='records')
with open('test.json', 'w') as f:
json.dump(df.to_dict(orient='records'), f, indent=4)
这导致
[
{
"en": "en1",
"th": "th1"
},
{
"en": "en2",
"th": "th2"
}
]
但我需要的结果是:
[
[ "en","th"],
[ "en1", "th1"],
[ "en2", "th2"]
]
如何修改代码以实现这一点
您当前有
df = pandas.read_csv('test.json', names=("en","th"))
,它试图使用一种读取CSV文件的方法来读取JSON。这应该是这将以JSON的形式读入数据并填充数据框。要写出它,您需要将第二行更新为:
然后可以删除
with
子句。然后,完整代码将是:但是,写入时将覆盖现有的源文件
感谢@Jeremy Caney对JSON有效性的澄清
相关问题 更多 >
编程相关推荐