我正在将CSV文件转换为JSON,如下所示:
import os
import csv
import json
with open(args.infile, encoding="utf-8") as csv_file:
csv_rows = list(csv.DictReader(csv_file))
with open(args.outfile, "w", encoding="utf-8") as json_file:
json.dump(csv_rows, json_file, ensure_ascii=False, indent=2)
CSV文件包含一个可以将值"true"
和"false"
作为字符串的列。这些应该以{{1}}和true
({strong>非,在false
或True
的Python样式中)映射到JSON。
我可以使用内置功能吗?
答案 0 :(得分:1)
我认为最简单的方法是在将csv文件的每一行传递给json.dump()
之前对其进行预处理,以将其中包含这些名称的字符串映射到Python布尔值 - json.dump()
将更改为您想要的JSON布尔值的类型。这就是我的意思:
import os
import csv
import json
with open(args.infile, newline='', encoding="utf-8") as csv_file:
csv_rows = [[True if row[field] == 'true' else
False if row[field] == 'false' else
row[field] for field in row] for row in csv.DictReader(csv_file)]
with open(args.outfile, "w", encoding="utf-8") as json_file:
json.dump(csv_rows, json_file, ensure_ascii=False, indent=2)
示例CSV输入:
Field Name1,Field Name2,Field Name3,Field Name4,Field Name5
1,2,true,3,4
5,6,false,7,8
9,10,non-bool,11,12
示例JSON输出:
[
[
"1",
"2",
true,
"3",
"4"
],
[
"5",
"6",
false,
"7",
"8"
],
[
"9",
"10",
"non-bool",
"11",
"12"
]
]