如何在Python中将对象的JSON数组更改为多维数组

2024-09-27 01:24:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码将读取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"]
]

如何修改代码以实现这一点


Tags: to代码testimportjsonpandasdf数组
1条回答
网友
1楼 · 发布于 2024-09-27 01:24:12

您当前有df = pandas.read_csv('test.json', names=("en","th")),它试图使用一种读取CSV文件的方法来读取JSON。这应该是

df = pandas.read_json('test.json')

这将以JSON的形式读入数据并填充数据框。要写出它,您需要将第二行更新为:

df.to_json('test.json', orient='values')

然后可以删除with子句。然后,完整代码将是:

import pandas
import json

df = pandas.read_json('test.json')
df.to_json('test.json', orient='values')

但是,写入时将覆盖现有的源文件

感谢@Jeremy Caney对JSON有效性的澄清

相关问题 更多 >

    热门问题