我有这个简单的python代码,可将json文件转换为csv。 我只想转换每个键的前四个值,但是我不知道该怎么做。
import json
import csv
# Opening JSON file and loading the data
# into the variable data
with open('personas.json') as json_file:
data = json.load(json_file)
employee_data = data['emp_details']
# now we will open a file for writing
data_file = open('data_file.csv', 'w')
# create the csv writer object
csv_writer = csv.writer(data_file)
# Counter variable used for writing
# headers to the CSV file
count = 0
for emp in employee_data:
if count == 0:
# Writing headers of CSV file
header = emp.keys()
csv_writer.writerow(header)
count += 1
# Writing data of CSV file
csv_writer.writerow(emp.values())
data_file.close()
这是json文件格式的示例
{"emp_details":[
{
"DATAID":"6908443",
"FIRST_NAME":"Fernando",
"SECOND_NAME":"Fabbiano",
"THIRD_NAME":"Agustin",
"FOURTH_NAME":"",
"AGE": "21",
"EMAIL": "fer.fab@gmail.com"
}
]}
正如我所说,我只想转换字段DATAID,FIRSTNAME,SECONDNAME,THIRD NAME。
答案 0 :(得分:0)
如果您不介意使用其他工具,那么最近使用esProc将json数据转换为csv会感到非常方便。您需要的示例代码:
test=file("test.json").read().import@j().emp_details
result=test.emp_details.new(DATAID, FIRST_NAME, SECOND_NAME, THIRD_NAME)
file("data_file.csv").export(result)