How to Convert JSON to CSV in Python: 3 Easy Methods

Are you looking for methods to convert JSON data into a CSV file? Let me help you!

JSON (JavaScript Object Notation) and CSV (Comma Separated Values) are two popular formats for storing and exchanging data. While JSON is preferred for its hierarchical structure and ease of integration with web APIs, CSV is known for its simplicity and compatibility with spreadsheet applications and data analysis tools.

How to Convert JSON to CSV in Python?

In Python, multiple methods exist for converting JSON data to a CSV file. Here are a few:

  • Using pandas
  • Using CSV Module
  • Using json_normalize() method

Let’s discuss these methods one by one!

Method 1: Using pandas

Pandas is an open-source Python library that is utilized for data manipulation and analysis. Its various data structures and functions make it quite easy to deal with structured data and extensive datasets.

In this method, we will make use of the pandas library for converting JSON to CSV. To do so:

  • First of all, import the pandas library and give it the alias “pd”.
  • After that, define a list of JSON-like dictionaries (JSON data) and convert it into a 2D DataFrame using the pandas “DataFrame()” method.
  • At last, write out this DataFrame into a file with a CSV extension.

Note: The parameter “index=False” prevents the index from being written to the CSV file.

import pandas as pd
json_data = [
    {"name": "Amir", "age": 12, "city": "Lahore"},
    {"name": "Anna", "age": 22, "city": "London"},
    {"name": "Mike", "age": 32, "city": "Chicago"}
]
# Converting JSON to DataFrame
df = pd.DataFrame(json_data)
# Saving to CSV
df.to_csv('output.csv', index=False)
converting json to csv in python using pandas library

Method 2: Using CSV Module

The CSV module offers supports to programmers with a lot of functionality for dealing with CSV files. For instance, it helps to read from and write to CSV files efficiently.

In order to use the CSV module for converting JSON to CSV:

  • Import the module into the code.
  • Define the JSON data you want to convert to CSV.
  • Then, use the “with” statement with write mode to create the file object where the CSV will be stored.
  • Create an instance of the DictWriter class from the CSV module and pass it the file object and field names sequentially.
  • Lastly, write the header and the rows containing the field names and the data respectively.
import csv
json_data = [
    { "order_id": "12222", "total_amount": 1000, "order_date": "2024-10-02" },
    { "order_id": "12346", "total_amount": 900, "order_date": "2024-09-02" }
]
# Converting JSON to CSV
with open('output.csv', 'w', newline='') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=["order_id", "total_amount", "order_date"])
    writer.writeheader()
    writer.writerows(json_data)
converting json to csv in python using csv module

Method 3: Using json_normalize() Method

json_normalize() is a pandas function that helps in flattening nested JSON data.

Here is how you can utilize it to convert JSON to CSV in Python:

  • Firstly, you’ve to import the “json_normalize()” function in to your program and define some nested JSON data.
  • Now, utilize the imported function to flatten the nested JSON data to a DataFrame (tabular format).
  • Lastly, save the resultant DataFrame in a CSV file. 
from pandas import json_normalize
nested_json = {
    "employees": [
        {"name": "Karin", "age": 32, "address": {"city": "New York", "postal_code": "121001"}},
        {"name": "Anna", "age": 22, "address": {"city": "London", "postal_code": "SW1A 1AA"}}
    ]
}
# Flattening the JSON
df = json_normalize(nested_json['employees'])
# Saving to CSV
df.to_csv('output.csv', index=False)
converting json to csv in python using json_normalize() method

Conclusion

There might be situations when you want to convert JSON data into CSV in Python. The “pandas” library, “CSV” module, and pandas “json_normalize()” function can be utilized for this purpose. Each method is elaborated along with its code snippet in this article.

Do let me know which method you liked the most!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
Scroll to Top