-2

I have file which contains the data in comma separated and i want final output to be json data. I tried below but wanted to know is there any better way to implement this?

data.txt

1,002, name, address
2,003, name_1, address_2
3,004, name_2, address_3

I want final output like below

{
"Id": "1",
"identifier": "002",
"mye": "name",
"add": "address"
}
{
"Id": "2",
"identifier": "003",
"mye": "name_2",
"add": "address_2"
}
and so on...

here is code which i am trying

list = []

with open('data.txt') as reader:
     for line in reader:
         list.append(line.split(','))
          
print(list)

above just return the list but i need to convert json key value pair defined in above

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
user1591156
  • 1,945
  • 4
  • 18
  • 31

4 Answers4

2

Your desired result isn't actually JSON. It's just a series of dict structures. What I think you want is a list of dictionaries. Try this:

fields = ["Id", "identifier", "mye", "add"]
my_json = []

with open('data.txt') as reader:
     for line in reader:
         vals = line.rstrip().split(',')
         my_json.append({fields[vals.index(val)]: val for val in vals})
print(my_json)
alfinkel24
  • 551
  • 5
  • 13
1

Something like this should work:

import json

dataList = []

with open('data.txt') as reader:
    # split lines in a way that strips unnecessary whitespace and newlines
    for line in reader.read().replace(' ', '').split('\n'):
        lineData = line.split(',')
        dataList.append({
            "Id":           lineData[0],
            "identifier":   lineData[1],
            "mye":          lineData[2],
            "add":          lineData[3]
        })
out_json = json.dumps(dataList)
print(out_json)

Note that you can change this line:

out_json = json.dumps(dataList)

to

out_json = json.dumps(dataList, indent=4)

and change the indent value to format the json output.

And you can write it to a file if you want to:

open("out.json", "w+").write(out_json)
Marko Borković
  • 1,884
  • 1
  • 7
  • 22
0

Extension to one of the suggestion, but you can consider zip instead of list comprehension

import json
my_json = []
dict_header=["Id","identifier","mye","add"]
with open('data.txt') as fh:
    for line in fh:
        my_json.append(dict ( zip ( dict_header, line.split('\n')[0].split(',')) ))

out_file = open("test1.json", "w")
json.dump(my_json, out_file, indent = 4, sort_keys = False)
out_file.close()

This of course assuming you save the from excel to text(Tab delimnited) in excel

1   2   name    address
2   3   name_1  address_2
3   4   name_2  address_3
mpx
  • 3,081
  • 2
  • 26
  • 56
-2

I would suggest using pandas library, it can't get any easier.

import pandas as pd

df = pd.read_csv("data.txt", header=None)

df.columns = ["Id","identifier", "mye","add"]

df.to_json("output.json")
klegoff
  • 51
  • 3