Convert Text file to JSON in Python
json module in Python. This module comes in-built with Python standard modules, so there is no need to install it externally.
See the following table given below to see serializing JSON i.e. the process of encoding JSON.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
|Python object||JSON object|
|int, long, float||numbers|
To handle the data flow in a file, the JSON library in Python uses
dump() function to convert the Python objects into their respective JSON object, so it makes easy to write data to files.
Various parameters can be passed to this method. They help in improving the readability of the JSON file. They are :
- dict object : the dictionary which holds the key-value pairs.
- indent : the indentation suitable for readability(a numerical value).
- separator : How the objects must be separated from each other, how a value must be seperated from its key. The symbols like “, “, “:”, “;”, “.” are used
- sort_keys : If set to true, then the keys are sorted in ascending order
Here the idea is to store the contents of the text as key-value pairs in the dictionary and then dump it into a JSON file. A simple example is explained below. The text file contains a single person’s details. The text1.txt file looks like:
Now to convert this to JSON file the code below can be used:
When the above code is executed, if a JSON file exists in the given name it is written to it, otherwise, a new file is created in the destination path and the contents are written to it.
Note the below line of code:
command, description = line.strip().split(None, 1)
Here split(None, 1) is used to trim off all excess spaces between a key-value pair and ‘1’ denotes split only once in a line. This ensures in a key-value pair, the spaces in the value are not removed and those words are not split. Only the key is separated from its value.
How to convert if multiple records are stored in the text file ?
Let us consider the following text file which is an employee record containing 4 rows.
The idea is to convert each employee’s detail into an intermediate dictionary and append that to one main resultant dictionary. For each intermediate dictionary a unique id is created and that serves as the key. Thus here the employee id and an intermediate dictionary make a key-value pair for the resultant dictionary to be dumped.
The attributes associated with each column is stored in a separate list called ‘fields’. In the above code, Each line is split on the basis of space and converted into a dictionary. Each time the line print(attributes) get executed, it appears as given below.
['Lisa', 'programmer', '34', '54000'] ['Elis', 'Trainee', '24', '40000'] ['Rickson', 'HR', '30', '47000'] ['Kate', 'Manager', '54', '63000']
The JSON file created by this code looks like :