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:
1 |
pip install json |
Now that the json module is installed, we can import it in our Python code with the following line of code:
1 |
import json |
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:
1 2 3 4 5 6 7 8 |
text_data = """Name=John Age=30 Country=USA""" data_dict = {} for line in text_data.split('\n'): key, value = line.split('=') data_dict[key] = value |
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:
1 |
json_data = json.dumps(data_dict, indent=4) |
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:
1 2 |
with open("data.json", "w") as file: file.write(json_data) |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import json text_data = """Name=John Age=30 Country=USA""" data_dict = {} for line in text_data.split('\n'): key, value = line.split('=') data_dict[key] = value json_data = json.dumps(data_dict, indent=4) with open("data.json", "w") as file: file.write(json_data) |
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.