How to Convert JSON String to TEXT File using Python

The following template can be used to convert a JSON string 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)

Next, you’ll see the steps to apply the above template in practice.

Steps to Convert JSON String to TEXT File using Python

Step 1: Prepare the JSON string

Let’s review a simple example, where we’ll create a JSON string based on the data below:

Product Price
Desktop Computer 700
Tablet 250
Printer 100
Laptop 1200

This is how the JSON string 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 string ready, save it within a JSON file.

For example, if you’re using Windows, then you may copy the JSON string into Notepad.

Then, save the notepad with your desired file name and add the .json 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 (in Windows):

pip install pandas

Step 4: Convert the JSON String to TEXT using Python

For the final step, you may use the following template to convert the JSON string 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 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 text file will be stored is: C:\Users\Ron\Desktop\Test\New_Products.txt
    Where ‘New_Products‘ is the new file name, and ‘txt‘ is the file extension

Note that you’ll need to modify the paths to reflect the location where the files will be stored on your computer.

Here is the complete code to convert the JSON string to a text file 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.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:

Product,Price
Desktop Computer,700
Tablet,250
Printer,100
Laptop,1200

You may also want to check the following guides for other types of conversions: