The following template can be used to convert a JSON file to a text file 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 TEXT file will be stored\New File Name.txt", index=False)
Steps to Convert JSON to TEXT using Python
Step 1: Prepare the JSON
Let’s review a simple example, where we’ll create a JSON based on the data below:
Product | Price |
Desktop Computer | 700 |
Tablet | 250 |
Printer | 100 |
Laptop | 1200 |
This is how the JSON data would look like:
{
"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 data ready, save it within a JSON file.
For example, if you’re using Windows, then you may copy the JSON data into a Notepad.
Then, save the notepad with your desired file name and add the “.json“ file extension at the end of the file name.
For example, let’s save the JSON file as Product_List.json
Step 3: Install the Pandas Package
If you haven’t already done so, install the Pandas package using this command:
pip install pandas
Step 4: Convert the JSON file to a TEXT file using Python
For the final step, you may use the following template to convert the JSON file to a text file 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 TEXT file will be stored\New File Name.txt", index=False)
For example, let’s convert the JSON file “Product_List.json” to a text file “New_Products.txt” (note that you’ll need to modify the paths to reflect the location where the files will be stored on your computer):
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.txt", index=False)
Once you run the code in Python (adjusted to your paths), you’ll get the new text file at your specified location.
And if you open the text file, you’ll see the same data as captured in step-1:
Desktop Computer,700
Tablet,250
Printer,100
Laptop,1200
You may also want to check the following guides for other types of conversions: