【问题标题】:Python to convert a CSV to multiple JSONS, one for each rowPython将CSV转换为多个JSONS,每行一个
【发布时间】:2021-07-07 16:12:55
【问题描述】:

我正在尝试使用 Python 将 CSV 转换为多个 JSON,CSV 的每一行一个 JSON。

我希望 JSON 文件名是第一列中的数据,而 JSON 内容是其余列。

所以我的 CSV 看起来像这样:

Filename, CustomerName, CustomerCode
Customer1.json,Customer1,C001
Customer2.json,Customer2,C002

我正在尝试获取两个 JSON,一个名为 Customer1.json,其内容为 Customer1, C001(JSON 格式)。

我现在离它很远,但我有这个:

import pandas as pd
import json

df = csvfile.csv
for i in df.index:
    result = df.to_json(orient="split")
    parsed = json.loads(result)
    json.dumps(parsed, indent=4)
    df.filename.to_json("row{}.json".format(i))

非常感谢任何帮助!

【问题讨论】:

  • 您能否包含一个示例输出文件内容?输出是 JSON 列表吗?

标签: python json pandas csv


【解决方案1】:

您可以迭代行。将“文件名”设置为索引,使剩下的行是你想要的json文件中的数据,并将每一行转换为一个列表。

import pandas as pd
import json
df = pd.read_csv("csvfile.csv", index_col="Filename")
for filename, value_series in df.iterrows():
    json.dump(value_series.to_list(), open(filename, "w"))

第一个 JSON 文件是

["Customer1", "C001"]

【讨论】:

  • 嗨,谢谢!我得到:“TypeError:TextIOWrapper 类型的对象不是 JSON 可序列化的”。我尝试更改为 json.dumps(open(filename), value_series.to_list()) 但后来我得到“TypeError:dumps() 需要 1 个位置参数,但给出了 2 个”。你能帮忙吗?
  • 已修复。我的 dump 参数顺序错误。
猜你喜欢
  • 2019-12-14
  • 2019-04-27
  • 2019-05-08
  • 2020-12-30
  • 2019-07-14
  • 1970-01-01
  • 1970-01-01
  • 2021-04-26
  • 2018-07-11
相关资源
最近更新 更多