Python JSON Convert Text file to JSON if multiple records are stored in the text file using python














































Python JSON Convert Text file to JSON if multiple records are stored in the text file using python



Convert Text file to JSON 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%u2019s 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.

# Python program to convert text 
# file to JSON


import json


# the file to be converted
filename = 'emp_detail1.txt'

# resultant dictionary
dict1 = {}

# fields in the sample file
fields =['name', 'designation', 'age', 'salary']

with open(filename) as fh:



# count variable for employee id creation
l = 1

for line in fh:

# reading line by line from the text file
description = list( line.strip().split(None, 4))

# for output see below
print(description)

# for automatic creation of id for each employee
sno ='emp'+str(l)

# loop variable
i = 0
# intermediate dictionary
dict2 = {}
while i<len(fields):

# creating dictionary for each employee
dict2[fields[i]]= description[i]
i = i + 1

# appending the record of each employee to
# the main dictionary
dict1[sno]= dict2
l = l + 1


# creating json file
out_file = open("test2.json", "w")
json.dump(dict1, out_file, indent = 4)
out_file.close()

The attributes associated with each column is stored in a separate list . 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.



The JSON file created by this code looks like :



 

Comments