Sai A Sai A
Updated date Nov 07, 2023
In this blog, we will learn how to convert JSON data into CSV format using Python. This blog offers multiple methods, complete with code examples and explanations.

Introduction:

JSON (JavaScript Object Notation) and CSV (Comma-Separated Values) are two popular data formats used to store and exchange data. Sometimes, you might need to convert JSON data into CSV format for easier processing, analysis, or sharing with others. In this blog, we will explore multiple methods to perform this conversion using Python.

Method 1: Using the pandas Library

The first method we will explore is using the pandas library. pandas is a powerful data manipulation and analysis library in Python that makes it easy to work with various data formats, including JSON and CSV.

Here's a Python program that demonstrates how to convert JSON to CSV using pandas:

import pandas as pd

# Sample JSON data
json_data = [
    {"name": "John", "age": 30, "city": "New York"},
    {"name": "Alice", "age": 25, "city": "Los Angeles"},
    {"name": "Bob", "age": 35, "city": "Chicago"},
]

# Create a DataFrame from the JSON data
df = pd.DataFrame(json_data)

# Convert the DataFrame to CSV
df.to_csv("output.csv", index=False)

print("JSON data converted to CSV successfully!")

Output:

The program will create a CSV file named "output.csv" in the current working directory. It will contain the JSON data in CSV format, without the index column.

  • We start by importing the pandas library as pd.

  • We define some sample JSON data as a list of dictionaries. Each dictionary represents a record with keys "name," "age," and "city."

  • Next, we create a pandas DataFrame using pd.DataFrame(json_data).

  • We use the to_csv method of the DataFrame to convert it to CSV format. The index=False argument ensures that the index column is not included in the CSV file.

  • Finally, we print a success message indicating that the JSON data has been converted to CSV.

Method 2: Using the csv Module

If you prefer a method that doesn't rely on external libraries, you can use Python's built-in csv module. This approach is straightforward and suitable for simple JSON to CSV conversions.

Here's a Python program using the csv module:

import csv

# Sample JSON data
json_data = [
    {"name": "John", "age": 30, "city": "New York"},
    {"name": "Alice", "age": 25, "city": "Los Angeles"},
    {"name": "Bob", "age": 35, "city": "Chicago"},
]

# Define the CSV file name
csv_file = "output.csv"

# Write JSON data to the CSV file
with open(csv_file, "w", newline="") as file:
    writer = csv.DictWriter(file, fieldnames=json_data[0].keys())
    writer.writeheader()
    writer.writerows(json_data)

print("JSON data converted to CSV successfully!")

Output:

The program will create a CSV file named "output.csv" in the current working directory, containing the JSON data in CSV format.

  • We start by importing the csv module.

  • Similar to Method 1, we define some sample JSON data as a list of dictionaries.

  • We specify the name of the CSV file as "output.csv."

  • We use a context manager (with) to open the CSV file for writing. The newline="" argument is used to ensure that line endings are handled correctly.

  • We create a csv.DictWriter object, specifying the field names based on the keys of the first dictionary in the JSON data. writeheader() is used to write the header row to the CSV file.

  • Finally, we use writerows to write the JSON data to the CSV file, one record at a time.

Method 3: Using a Third-Party Library (e.g., json2csv)

While the previous methods are efficient for small to medium-sized datasets, there are situations where you may encounter more complex JSON structures that require additional customization during the conversion process. In such cases, using a third-party library like json2csv can be beneficial. This library allows you to define custom mappings and transformations for your JSON data.

Here's how you can use the json2csv library for JSON to CSV conversion:

First, you need to install the json2csv library using pip:

pip install json2csv

Now, you can create a Python program to use the library:

from json2csv import json2csv

# Sample JSON data
json_data = [
    {"name": "John", "age": 30, "city": "New York"},
    {"name": "Alice", "age": 25, "city": "Los Angeles"},
    {"name": "Bob", "age": 35, "city": "Chicago"},
]

# Define the CSV file name
csv_file = "output.csv"

# Define custom mapping (if needed)
mapping = {
    "name": "Person's Name",
    "age": "Age",
    "city": "City",
}

# Convert JSON to CSV using custom mapping
json2csv(json_data, csv_file, mapping)

print("JSON data converted to CSV successfully!")

Output:

The program will create a CSV file named "output.csv" in the current working directory, containing the JSON data in CSV format with custom column names (if specified).

  • We import the json2csv function from the json2csv library.

  • As in previous methods, we define some sample JSON data.

  • We specify the name of the CSV file as "output.csv."

  • If you need custom column names or want to reorder columns, you can define a mapping dictionary. In this example, we provide a mapping that renames the columns to "Person's Name," "Age," and "City."

  • We use the json2csv function, passing the JSON data, CSV file name, and the optional mapping as arguments to perform the conversion.

  • Finally, we print a success message indicating that the JSON data has been converted to CSV.

Conclusion:

In this blog, we have explored multiple methods for converting JSON data to CSV in Python. Whether you prefer the simplicity of using pandas, the basic approach with the built-in csv module, or the flexibility of a third-party library like json2csv, you have options to suit your needs.

Comments (0)

There are no comments. Be the first to comment!!!