python convert json to csv
Python: Convert JSON to CSV
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy to read and write for humans and machines. CSV (Comma Separated Values) is a file format that stores tabular data, such as spreadsheets or databases.
Method 1: Using the csv Module
The easiest way to convert JSON data to CSV format in Python is by using the csv module from the standard library. The csv module provides functionality to read from and write to CSV files.
import csv
import json
# Open the JSON file and read the data
with open('data.json', 'r') as f:
data = json.load(f)
# Open the CSV file and write the data
with open('data.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(data[0].keys()) # Write the header row
for item in data:
writer.writerow(item.values())
This code reads a JSON file named 'data.json' and writes its contents to a CSV file named 'data.csv'. The first row of the CSV file contains the header row with the keys of the JSON objects, and each subsequent row contains the values of each object.
Method 2: Using pandas
Pandas is a popular data manipulation library in Python that provides high-performance, easy-to-use data structures and data analysis tools. It can also handle JSON data and convert it to CSV format.
import pandas as pd
import json
# Open the JSON file and read the data
with open('data.json', 'r') as f:
data = json.load(f)
# Convert the JSON data to a pandas DataFrame
df = pd.DataFrame(data)
# Write the DataFrame to a CSV file
df.to_csv('data.csv', index=False)
This code reads a JSON file named 'data.json' and converts its contents to a pandas DataFrame. Then it writes the DataFrame to a CSV file named 'data.csv'. The 'index=False' argument prevents pandas from writing the row index to the CSV file.
Conclusion
Both methods discussed above are easy ways to convert JSON data to CSV format in Python. Depending on the size and complexity of your data, one method may be more suitable than the other. The csv module is simpler and more lightweight, while pandas provides more advanced data manipulation tools.