To convert a json to csv in Pandas, you need to “convert a json data to a Python object using the json.loads()” function, then “convert an object to DataFrame using the pd.DataFrame(data)”, and use the pd.to_csv() function to convert a data frame to csv.
Example
import pandas as pd
import json
# Sample JSON data
json_data = '''
[
{"name": "Krunal", "age": 30, "city": "New York"},
{"name": "Ankit", "age": 28, "city": "San Francisco"},
{"name": "Rushabh", "age": 31, "city": "Los Angeles"}
]
'''
# Load JSON data into a Python object
data = json.loads(json_data)
# Convert Python object to a Pandas DataFrame
data_frame = pd.DataFrame(data)
# Save the DataFrame as a CSV file
data_frame.to_csv('output.csv', index=False)
print("JSON data has been converted to CSV and saved to 'output.csv'")
Output
JSON data has been converted to CSV and saved to 'output.csv'
And in your current project folder, you will see a CSV file called output.csv which looks like this:
name,age,city
Krunal,30,New York
Ankit,28,San Francisco
Rushabh,31,Los Angeles
In this example, we first loaded the JSON data into a Python object using the json.loads() function. We then converted the JSON data to a Pandas DataFrame using the pd.DataFrame() function.
Finally, we used the to_csv() method of the DataFrame to save the data as a CSV file.
This approach works well for JSON data containing a list of dictionaries with the same structure. However, if your JSON data has a different structure or is nested, you can use Pandas’ pd.json_normalize() function to flatten the nested JSON data before converting it to a DataFrame.
That’s it.