How To Convert Text To JSON In Python

In this tutorial, we will learn how to convert text data into JSON format using Python. JSON, which stands for JavaScript Object Notation, is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate.

We will explore how to use Python’s inbuilt json module to convert text data into JSON format efficiently.

Step 1: Install and import the ‘json’ module

Before we can start using the Python json module, we need to install it using pip package manager. Run the following command to install the json module:

Now that the json module is installed, we can import it in our Python code with the following line of code:

Step 2: Convert text data to a Python dictionary

Once we have the json module imported, we can start converting text data to JSON format. First, let’s convert our text data to a Python dictionary. The text data should be in a key-value pair format, separated by an equals sign (=).

Here’s an example of some sample text data:

Name=John
Age=30
Country=USA

The Python code to convert this text data into a dictionary would be:

Now our text data is represented as a dictionary in Python.

Step 3: Convert Python dictionary to JSON string

To convert our Python dictionary to a JSON string, we can use the json.dumps() function provided by the json module. The code will look like this:

Here, we have used the ‘indent’ parameter to make the JSON output more human-readable. You can adjust the indent value according to your preference, or remove it completely for a more compact JSON string.

Step 4: Save JSON data to file (Optional)

If you want to save the JSON data to a file, you can use the following code:

This code will create a new JSON file called “data.json” in the same directory as your Python script and write the JSON data to that file.

Full code example

Output

When you execute the code above, you’ll get a new file called “data.json” with the following content:

{
    "Name": "John",
    "Age": "30",
    "Country": "USA"
}

Conclusion

Now you know how to convert text data into JSON format in Python using the json module. Converting text data into JSON format can be extremely useful when working with APIs or storing data in a more structured format. With the help of Python’s built-in json module and a few lines of code, you can easily achieve this conversion.