我有一个包含数据的 CSV 文件 -
Time,site_name,cell_name,RRC_attempts,rrc_succ_rate
2018-01-12T08:37:00-06:00,910536_ARPIN,910536-24,1,100.0
2018-01-12T08:37:00-06:00,910536_ARPIN,910536-34,0,0.0
2018-01-12T08:37:00-06:00,910536_ARPIN,910536-14,5,100.0
我正在使用 python 中的 json 模块将此 csv 转换为 json
import json
import csv
csvfile_ind = open("test.csv",'r')
reader_ind = csv.DictReader(csvfile_ind)
json_file_ind = open("test_json.json", 'w')
for row in reader_ind:
json_file_ind.write(json.dumps(row,sort_keys=False, indent=4, separators=(',', ': ')))
我当前的输出是 -
[
{
"Time": "2018-01-12T08:37:00-06:00",
"site_name": "910536_ARPIN",
"cell_name": "910536-24",
"RRC_attempts": "1",
"rrc_succ_rate": "100.0"
},
{
"Time": "2018-01-12T08:37:00-06:00",
"site_name": "910536_ARPIN",
"cell_name": "910536-34",
"RRC_attempts": "0",
"rrc_succ_rate": "0.0"
},
{
"Time": "2018-01-12T08:37:00-06:00",
"site_name": "910536_ARPIN",
"cell_name": "910536-14",
"RRC_attempts": "5",
"rrc_succ_rate": "100.0"
}
]
我想要的输出是 -
[
{
"Time": "2018-01-12T08:37:00-06:00",
"site_name": "910536_ARPIN",
"cell_name": "910536-24",
"RRC_attempts": 1,
"rrc_succ_rate": 100
},
{
"Time": "2018-01-12T08:37:00-06:00",
"site_name": "910536_ARPIN",
"cell_name": "910536-34",
"RRC_attempts": 0,
"rrc_succ_rate": 0
},
{
"Time": "2018-01-12T08:37:00-06:00",
"site_name": "910536_ARPIN",
"cell_name": "910536-14",
"RRC_attempts": 5,
"rrc_succ_rate": 100
}
]
如何告诉 json 将数字解析为 int 或 float 而不是字符串?请指教。注意 - 在编写 CSV 文件时,我使用 int() 或 float() 显式将值转换为 int 或 float。
不要将每一行编写为对 json.dumps()
的单独调用。将所有行收集到一个列表中,然后一次性全部转储。
要将字符串字段转换为整数,请对 dict
中的这些条目调用 int()
。
import json
import csv
with csvfile_ind = open("test.csv",'r'):
reader_ind = csv.DictReader(csvfile_ind)
rows = []
for row in reader_ind:
row["RRC_attempts"] = int(row["RRC_attempts"])
row["rrc_succ_rate"] = int(row["rrc_succ_rate"])
rows.append(row)
with json_file_ind = open("test_json.json", 'w'):
json.dump(rows, json_file_ind, sort_keys=False, indent=4, separators=(',', ': '))
我是一名优秀的程序员,十分优秀!