How to Convert JSON String to CSV using Python
In this short tutorial, you will learn how to convert a JSON string to CSV using Python.
TLDR solution
import pandas as pd
df = pd.read_json("path-to-file/file-name.json")
df.to_csv("path-to-file/csv-file-name.csv", index=False)
Step-by-Step Example
Step 1: Install the pandas Package
If you don't have pandas already installed, execute the following command in your terminal:
pip install pandas
Step 2: Prepare a JSON File
Let's say, you want a JSON file based on the following information:
| Fish | LifespanYears |
|---|---|
| salmon | 5 |
| pufferfish | 10 |
| shark | 25 |
The corresponding JSON string is as follows:
{
"Fish": {
"0": "salmon",
"1": "pufferfish",
"2": "shark"
},
"LifespanYears": {
"0": 5,
"1": 10,
"2": 25
}
}
Create a new file using a text editor of your choice, copy-paste the above JSON string into it, and save it as fish_lifespan.json on your desktop.
VoilĂ , you just created a JSON file.
Step 3: Create a Python Script that Converts JSON to CSV
Let's create a Python script that converts the JSON file on your desktop to a CSV file:
import os
import pandas as pd
desktop_path = os.path.expanduser("~/Desktop")
df = pd.read_json(desktop_path + "/fish_lifespan.json")
df.to_csv(desktop_path + "/fish_lifespan.csv", index=False)
Create a new file using a text editor of your choice, copy-paste the above Python code into it, and save it as json2csv.py on your desktop.
Verify that it works by navigating your terminal to your desktop and running the script:
cd Desktop
python json2csv.py
That's it! You should now find a CSV file on your desktop.