Reading and Writing JSON Files in Python
Interview Question: Write a Python script to process a JSON file containing customer data and convert it into a structured DataFrame.
json file can either be created via Nested Dictionaries or lists of Dictionaries
Step 1: Example of 'Nested Dictionaries'
patients = {
"Name":{"0":"John","1":"Nick","2":"Ali","3":"Joseph"},
"Gender":{"0":"Male","1":"Male","2":"Female","3":"Male"},
"Nationality":{"0":"UK","1":"French","2":"USA","3":"Brazil"},
"Age" :{"0":10,"1":25,"2":35,"3":29}
}
Example of 'Lists of Dictionaries':
Creating JSON Data via Lists of Dictionaries
cars = [
{"Name":"Honda", "Price": 10000, "Model":2005, "Power": 1300},
{"Name":"Toyota", "Price": 12000, "Model":2010, "Power": 1600},
{"Name":"Audi", "Price": 25000, "Model":2017, "Power": 1800},
{"Name":"Ford", "Price": 28000, "Model":2009, "Power": 1200},
]
Step 2: Writing to patients.json file:
# Writing to sample.json
import json
with open('patients.json', 'w') as f:
json.dump(patients, f)
Step 3: Reading the json file:
import pandas as pd
patients_df = pd.read_json('patients.json')
print(patients_df.head())
Output:
Name Gender Nationality Age
0 John Male UK 10
1 Nick Male French 25
2 Ali Female USA 35
3 Joseph Male Brazil 29
Step 4: Save the dateframe into the .csv file:
# Save DataFrame to CSV
patients_df.to_csv('output_file.csv', index=False)
patients_df_csv = pd.read_csv('output_file.csv')
print(patients_df_csv.head())
Output:
Name Gender Nationality Age
0 John Male UK 10
1 Nick Male French 25
2 Ali Female USA 35
3 Joseph Male Brazil 29