Python: How to Convert JSON to CSV and CSV to JSON (Tutorial)

Python: How to Convert JSON to CSV and CSV to JSON (Tutorial)
Photo by Vincent van Zalinge / Unsplash

There are several reasons why you might need to convert JSON to CSV and vice versa in Python:

  1. Data Transformation: JSON and CSV are two common formats for storing and exchanging data. Converting between them allows you to transform and manipulate data in different ways based on your needs.
  2. Data Integration: JSON and CSV files are often used to import or export data from different systems. Converting between formats enables you to seamlessly integrate data from various sources or transfer data between different applications.
  3. Data Analysis: JSON and CSV files can be used as input for data analysis tasks. Depending on the requirements of your analysis, you may need to convert data from one format to another to perform specific operations or apply analytical techniques.
  4. Data Storage: JSON and CSV files have different characteristics and use cases for data storage. JSON is a more flexible and hierarchical format, suitable for complex data structures. On the other hand, CSV is a tabular format that is more compact and efficient for large datasets. Converting between formats allows you to optimize data storage based on your specific requirements.

By being able to convert JSON to CSV and CSV to JSON in Python, you have the flexibility to work with different data formats and leverage the strengths of each format for your specific use cases.

There are several reasons why you might need to convert JSON to CSV and vice versa in Python:

  1. Data Transformation: JSON and CSV are two common formats for storing and exchanging data. Converting between them allows you to transform and manipulate data in different ways based on your needs.
  2. Data Integration: JSON and CSV files are often used to import or export data from different systems. Converting between formats enables you to seamlessly integrate data from various sources or transfer data between different applications.
  3. Data Analysis: JSON and CSV files can be used as input for data analysis tasks. Depending on the requirements of your analysis, you may need to convert data from one format to another to perform specific operations or apply analytical techniques.
  4. Data Storage: JSON and CSV files have different characteristics and use cases for data storage. JSON is a more flexible and hierarchical format, suitable for complex data structures. On the other hand, CSV is a tabular format that is more compact and efficient for large datasets. Converting between formats allows you to optimize data storage based on your specific requirements.

By being able to convert JSON to CSV and CSV to JSON in Python, you have the flexibility to work with different data formats and leverage the strengths of each format for your specific use cases.

In this tutorial, we will use basic Python modules. However, you can also utilize the Pandas library, which is popular among data engineers and data scientists.

Requirements

To convert JSON to CSV and vice versa in Python, you can use the json and csv modules.

import json
import csv

JSON to CSV

Here are the steps to convert JSON to CSV using the provided example:

  1. Open the JSON file named "data.json" in read mode.
  2. Load the JSON data into the data variable.
  3. Open the CSV file named "data.csv" in write mode.
  4. Create a CSV writer object.
  5. Write the CSV header by extracting the keys from the first item in the data list.
  6. Write the CSV data by extracting the values from each item in the data list.

These steps will allow you to convert JSON to CSV using Python.

import json
import csv

# Open the JSON file
with open("data.json", "r") as json_file:
    # Load the JSON data
    data = json.load(json_file)

# Open the CSV file
with open("data.csv", "w", newline="") as csv_file:
    # Create a CSV writer
    writer = csv.writer(csv_file)

    # Write the CSV header
    writer.writerow(data[0].keys())

    # Write the CSV data
    for item in data:
        writer.writerow(item.values())

CSV to JSON

Here are the steps to convert CSV to JSON using the provided example:

  1. Open the CSV file named "data.csv" in read mode.
  2. Create a CSV reader object.
  3. Skip the header row using next(reader).
  4. Initialize an empty list data to store the JSON data.
  5. Read each row in the CSV file.
  6. Create a dictionary item for each row by mapping the header values to the corresponding row values.
  7. Add the dictionary item to the data list.
  8. Open the JSON file named "data.json" in write mode.
  9. Use the json.dump() function to write the data list as JSON data to the file.
import csv
import json

# Open the CSV file
with open("data.csv", "r") as csv_file:
    # Create a CSV reader
    reader = csv.reader(csv_file)

    # Skip the header row
    header = next(reader)

    # Initialize an empty list for the JSON data
    data = []

    # Read each row in the CSV file
    for row in reader:
        # Create a dictionary for each row
        item = {}
        for i in range(len(header)):
            item[header[i]] = row[i]
        # Add the dictionary to the data list
        data.append(item)

# Open the JSON file
with open("data.json", "w") as json_file:
    # Write the JSON data
    json.dump(data, json_file, indent=4)

Remember to always close the files after reading or writing to them to free up system resources.

These examples should give you a basic understanding of how to convert JSON to CSV and CSV to JSON in Python. For more advanced usage and additional options, refer to the Python documentation on the json and csv modules.

Resources

csv — CSV File Reading and Writing
Source code: Lib/csv.py The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. CSV format was used for many years prior to att…
json — JSON encoder and decoder
Source code: Lib/json/__init__.py JSON (JavaScript Object Notation), specified by RFC 7159(which obsoletes RFC 4627) and by ECMA-404, is a lightweight data interchange format inspired by JavaScript…







Open-source Apps

9,500+

Medical Apps

500+

Lists

450+

Dev. Resources

900+

Read more