In this short guide, you’ll see the steps to convert a JSON string to CSV using Python.
To begin, you may use the following template to perform the conversion:
import pandas as pd df = pd.read_json(r"Path where the JSON file is saved\File Name.json") df.to_csv(r"Path where the new CSV file will be stored\New File Name.csv", index=False)
Steps to Convert a JSON String to CSV using Python
Step 1: Prepare a JSON String
To start, prepare a JSON string that you’d like to convert to CSV.
For example, let’s say that you’d like to prepare a JSON string based on the following information about different products:
Product | Price |
Desktop Computer | 700 |
Tablet | 250 |
Printer | 100 |
Laptop | 1200 |
This is how the JSON string would look like for our example:
{ "Product": { "0": "Desktop Computer", "1": "Tablet", "2": "Printer", "3": "Laptop" }, "Price": { "0": 700, "1": 250, "2": 100, "3": 1200 } }
Step 2: Create the JSON File
Once you have your JSON string ready, save it within a JSON file.
Alternatively, you may copy the JSON string into Notepad, and then save that file with a .json extension.
For our example, save the notepad as Product_List.json.
Step 3: Install the Pandas Package
If you haven’t already done so, install the Pandas package. You may use the following command to install the Pandas package:
pip install pandas
Step 4: Convert the JSON String to CSV using Python
You may now use the following template to convert the JSON string to CSV using Python:
import pandas as pd df = pd.read_json(r"Path where the JSON file is saved\File Name.json") df.to_csv(r"Path where the new CSV file will be stored\New File Name.csv", index=False)
For our example:
- The path where the JSON file is saved is: C:\Users\Ron\Desktop\Test\Product_List.json
- Where ‘Product_List‘ is the file name, and ‘.json‘ is the file extension
- The path where the new CSV file will be stored is: C:\Users\Ron\Desktop\Test\New_Products.csv
- Where ‘New_Products‘ is the new file name, and ‘.csv‘ is the file extension
Note that you’ll need to adjust the paths to reflect the location where the files will be stored on your computer.
Here is the complete Python code to perform the conversion to CSV for our example:
import pandas as pd df = pd.read_json(r"C:\Users\Ron\Desktop\Test\Product_List.json") df.to_csv(r"C:\Users\Ron\Desktop\Test\New_Products.csv", index=False)
Run the code (adjusted to your paths) and you’ll see the new CSV file at your specified location.
Once you open the file, you’ll get the data about the products:
Product | Price |
Desktop Computer | 700 |
Tablet | 250 |
Printer | 100 |
Laptop | 1200 |
You may also want to check the following guides for other types of file conversions: