【问题标题】:Json file not save complete when try to pass .csv to Json尝试将 .csv 传递给 Json 时,Json 文件未保存完整
【发布时间】:2023-01-12 02:01:37
【问题描述】:

嗨,我想创建一个 json 文件,但是当我打印结果时,结果是完整的,但是当我保存在文件 .json 中时,文件只保存数据的最后一个键

import json
import csv


jsonFile = r'Prueba.json'

with open('file1.csv', newline='') as csvfile:
    datos = csv.DictReader(csvfile)
    for row in datos:
        datos_jason = json.dumps(row, indent=4, skipkeys = True)
        print(datos_jason)

        with open(jsonFile, 'w', encoding='utf-8') as jsonf:
            jsonf.write(json.dumps(row, indent=4))

在终端

{
"companyemail": "user 1",
"password": "12345",
"firstname": "Don10",
"lastname": "Api10"
}
{
"companyemail": "user 2",
"password": "12345",
"firstname": "Don11",
"lastname": "Api11"
}
{
"companyemail": "user 3",
"password": "12345",
"firstname": "Don12",
"lastname": "Api12"
}
{
"companyemail": "user 4",
"password": "12345",
"firstname": "Don13",
"lastname": "Api13"
}
{
"companyemail": "user 5",
"password": "12345",
"firstname": "Don14",
"lastname": "Api14"
}

但是在 json 文件中

{
"companyemail": "user 5",
"password": "12345",
"firstname": "Don14",
"lastname": "Api14"
}

在文件中只保存最后的用户

我添加 csv 文件

companyemail,password,firstname,lastname
user 1,12345,Don10,Api10
user 2,12345,Don11,Api11
user 3,12345,Don12,Api12
user 4,12345,Don13,Api13
user 5,12345,Don14,Api14

我是编程新手,我想将此 json 格式推送到带有 API 的 POST,这些部分工作正常但只上传最后一个用户

【问题讨论】:

  • 这回答了你的问题了吗? How do I append to a file?
  • 或者更好的方法是一次性将所有 datos 写入一个文件,而不是逐行写入(无论如何都会产生无效的 JSON)。

标签: python json csv dictionary


【解决方案1】:

如果你想要一个包含一个对象列表的 JSON 文件,你可以将整个 CSV 阅读器读入一个列表,然后dump

import json
import csv

with open("file1.csv") as csvfile:
    with open(r"Prueba.json", "w", encoding="utf-8") as jsonf:
        data = list(csv.DictReader(csvfile))
        json.dump(data, jsonf, indent=4)

如果你想要一个JSONL/ND-JSON file, e.g. one JSON document per line

import json
import csv

with open("file1.csv") as csvfile:
    with open(r"Prueba.json", "w", encoding="utf-8") as jsonf:
        for line in csv.DictReader(csvfile):
            print(json.dumps(line), file=jsonf)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    相关资源
    最近更新 更多