This following code sample will guide you on how to convert a tab delimited text file to JSON format, with the following JSON file structure, using of Python programming.
1 2 3 4 5 6 7 |
[ { "key": "value", "key": "value", "key": "value" } ] |
First, let create a text file with tab delimited as following:
1 2 3 4 5 6 |
Name EmpId Department John 00383 Engineering Linda 00385 Finance Samuel 00387 Marketing Casey 00389 Management Albert 00390 Support |
Save the file as employee.txt
Now, create a .py file with the following python code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
import csv # save the json output as emp.json jsfile = file('emp.json', 'w') jsfile.write('[\r\n') with open('employee.txt','r') as f: next(f) # skip headings reader=csv.reader(f,delimiter='\t') # get the total number of rows excluded the heading row_count = len(list(reader)) ite = 0 # back to first position f.seek(0) next(f) # skip headings for name,empid,dept in reader: ite+= 1 jsfile.write('\t{\r\n') n = '\t\t\"name\": \"' + name + '\",\r\n' i = '\t\t\"empid\": \"' + empid + '\",\r\n' d = '\t\t\"department\": \"' + dept + '\"\r\n' jsfile.write(n) jsfile.write(i) jsfile.write(d) jsfile.write('\t}') # omit comma for last row item if ite < row_count: jsfile.write(',\r\n') jsfile.write('\r\n') jsfile.write(']') jsfile.close() |
Save the file as text2json.py
To execute text2json.py, run it using the python command as following:
python text2json.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
[ { "name": "John", "empid": "00383", "department": "Engineering" }, { "name": "Linda", "empid": "00385", "department": "Finance" }, { "name": "Samuel", "empid": "00387", "department": "Marketing" }, { "name": "Casey", "empid": "00389", "department": "Management" }, { "name": "Albert", "empid": "00390", "department": "Support" } ] |
Download sample source code: txt2json.zip
Converting Tab Delimited Textfile to JSON