Python 将json文件转换为csv
我有一个简单的python代码,可以将json文件转换为csv。 我只想转换每个键的前四个值,但我不知道如何转换Python 将json文件转换为csv,python,json,csv,Python,Json,Csv,我有一个简单的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 =
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。这其中的哪一部分试图“只转换每个键的前四个值”?实际上不是。我试过的一切都不管用。此代码转换每个键的所有de值。这个问题还不够清楚吗?很抱歉,您可以提供一些关于json文件格式的更多信息吗?也许是一个例子(可以是虚构的数据)?是的,当然。感谢您花时间阅读我的问题。如果您想坚持使用现有代码,您可能需要使用
csv.DictWriter