Home > OS >  Converting text file to json
Converting text file to json

Time:10-19

I have text file and I want to convert it to JSON:

red|2022-09-29|03:15:00|info 1
blue|2022-09-29|10:50:00|
yellow|2022-09-29|07:15:00|info 2

so i type a script to convert this file into JSON:

import json
  
filename = 'input_file.txt'
 
dict1 = {}
 
fields =['name', 'date', 'time', 'info']
 
with open(filename) as fh:
     
 
     
    l = 1
     
    for line in fh:
         
        description = list( line.strip().split("|", 4))
         
        print(description)
         
        sno ='name' str(l)
     
        i = 0
        dict2 = {}
        while i<len(fields):
             
                dict2[fields[i]]= description[i]
                i = i   1
                 

        dict1[sno]= dict2
        l = l   1
 
 
out_file = open("json_file.json", "w")
json.dump(dict1, out_file, indent = 4)
out_file.close()

and output looks like this:

{
    "name1": {
        "name": "red",
        "date": "2022-09-29",
        "time": "03:15:00",
        "info": "info 1"
    },
    "name2": {
        "name": "blue",
        "date": "2022-09-29",
        "time": "10:50:00",
        "info": ""
    },
    "name3": {
        "name": "yellow",
        "date": "2022-09-29",
        "time": "07:15:00",
        "info": "info 2"
    }
}

As you can see I do so, but now I want to change looks of this JSON file. How can I change it to make my output looks like this: to look like this:

[
    {"name":"red", "date": "2022-09-29", "time": "03:15:00", "info":"info 1"},
    {"name":"blue", "date": "2022-09-29", "time": "10:50:00", "info":""},
    {"name":"yellow", "date": "2022-09-29", "time": "07:15:00", "info":"info 2"}
]

CodePudding user response:

I would use pandas, it allows you to solve your problem in one statement and avoid reinventing a wheel:

import pandas as pd
pd.read_table("input_file.txt", sep="|", header=None, 
              names=["name", "date" , "time", "info"]).fillna("")\
  .to_json("json_file.json", orient="records")

CodePudding user response:

If you see your required json output, it is a list and not a dict like you have right now. So using a list(data) instead of dict(dict1) should give the correct output.

Following updated code should generate the json data in required format -

import json

filename = 'input_file.txt' 
data = []
fields =['name', 'date', 'time', 'info']
 
with open(filename) as fh:
    l = 1
    for line in fh:
        description = list( line.strip().split("|", 4))
        print(description)
        sno ='name' str(l)
        i = 0
        dict2 = {}
        while i<len(fields):
            dict2[fields[i]]= description[i]
            i = i   1
        data.append(dict2)
        l = l   1
 
out_file = open("json_file.json", "w")
json.dump(data, out_file, indent = 4)
out_file.close()
  • Related