json to csv

json(JavaScript Object Notion)文件格式:

data = {"employee_details":[{"employee_name": "James", "email": "james@gmail.com", "job_profile": "Sr. Developer"},
                            {"employee_name": "Smith", "email": "Smith@gmail.com", "job_profile": "Project Lead"}]}

读取json文件

file_need = "/Users/~/Desktop/employee.json"
with open(file_need) as json_file1:
    json_data = json.load(json_file1)
emp_data = json_data[employee_details]
# print(emp_data)

新建csv文件, 并写入

employ_data = open(/tmp/EmployData.csv, w)
csvwriter = csv.writer(employ_data)

count = 0
for emp in emp_data:
    if count == 0:
        header = emp.keys()
        csvwriter.writerow(header)
        count += 1
    csvwriter.writerow(emp.values())

employ_data.close()

完成后 go to finder /tmp/EmployData.csv 查看文件

附: 完整代码

# 把json 文件转化为csv 文件

‘‘‘ json(JavaScript Object Notation) 文件格式
data = ‘{"employee_details":[{"employee_name": "James", "email": "james@gmail.com", "job_profile": "Sr. Developer"},
                            {"employee_name": "Smith", "email": "Smith@gmail.com", "job_profile": "Project Lead"}]}‘
‘‘‘

import json,csv

employee_data = {"employee_details":[{"employee_name": "James", "email": "james@gmail.com", "job_profile": "Sr. Developer"},{"employee_name": "Smith", "email": "Smith@gmail.com", "job_profile": "Project Lead"}]}
employee_parsed = json.loads(employee_data)
emp_data = employee_parsed[employee_details]
# print(emp_data)

# open a file for writing

employ_data = open(/tmp/EmployData.csv, w)

# create the csv writer object

csvwriter = csv.writer(employ_data)

count = 0

for emp in emp_data:
    if count == 0:
        header = emp.keys()
        csvwriter.writerow(header)
        count += 1

    csvwriter.writerow(emp.values())

employ_data.close()

json to csv

上一篇:(七).netcore+vue 跨域调用——CORS


下一篇:(十).netcore+vue vue-cli@4+element-ui+router+vuex