Json文件不保存完整时,试图传递.csv到Json



嗨,我想创建一个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格式推送到POST与API,这些部分工作正常,但只上传最后一个用户

如果您想要一个包含一个对象列表的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文件,例如每行一个JSON文档,

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)

相关内容

  • 没有找到相关文章

最新更新