Python JSON Convert Text file to JSON in Python














































Python JSON Convert Text file to JSON in Python



Convert Text file to JSON in Python

To convert a text file into JSON, there is a json module in Python. This module comes in-built with Python standard modules, so there is no need to install it externally.

Syntax:   json.dump()                                                                                                                        

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 details. The emp_details.txt file looks like:


 

Now to convert this to JSON file the code below can be used:

# Python program to convert text 
# file to JSON
import json


# the file to be converted to
# json format
filename = 'emp_details.txt'

# dictionary where the lines from
# text will be stored
dict1 = {}

# creating dictionary
with open(filename) as fh:

for line in fh:

# reads each line and trims of extra the spaces
# and gives only the valid words
command, description = line.strip().split(None, 1)

dict1[command] = description.strip()

# creating json file
# the JSON file is named as test1
out_file = open("test1.json", "w")
json.dump(dict1, out_file, indent = 4, sort_keys = False)
out_file.close()


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.

Output:


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 '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.



Comments