Convert json file to csv

Viewed 194

I have this simple python code that converts a json file into a csv. I would like to convert only the first four values of each key, but i couldn't figure out how to do it.

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() 

Here is an example of json file's format

{"emp_details":[
    {
     "DATAID":"6908443",
     "FIRST_NAME":"Fernando",
     "SECOND_NAME":"Fabbiano",
     "THIRD_NAME":"Agustin",
     "FOURTH_NAME":"", 
     "AGE": "21", 
     "EMAIL": "fer.fab@gmail.com"
    }
]}

And as i said, i would like to convert only the fields DATAID, FIRSTNAME, SECONDNAME, THIRD NAME.

0 Answers
Related