Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Text file to JSON

I am trying to convert my list of strings in a file to a certain JSON data format.
My sample.txt file contains this data:

1234

5678

9765

I wanted to converted it in to the following form formated.json:

{
  "x": "1234",
  "y": "a"
},
{
  "x": "5678",
  "y": "a"
},
{
  "x": "9765",
  "y": "a"
}

Here is my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import itertools
import json

with open('sample.txt', 'r') as f_in, open('formated.json', 'w') as f_out:
    for x, y in itertools.zip_longest(*[f_in]*2):
        record = {
            "x": x.strip(),
            "y": "a",
        }
        f_out.write(json.dumps(record, indent=2))
        f_out.write(',\n')

How ever this script jumps every next line from the text file and out puts:

 {
      "x": "1234",
      "y": "a"
    },
    {
      "x": "9765",
      "y": "a"
    }

However, I would like my script to read all lines and out put the result.

>Solution :

Just use the line contents, do not use zip:

import json

result = []
with open('sample.txt', 'r') as f_in:
    for line in f_in:
        line = line.strip()
        if not line:
            continue  # skip empty lines

        result.append({'x': line, 'y': 'a'})

with open('formated.json', 'w') as f_out:
    print(json.dumps(result, indent=2))
    #f_out.write(json.dumps(result, indent=2))

Out:

[
  {
    "x": "1234",
    "y": "a"
  },
  {
    "x": "5678",
    "y": "a"
  },
  {
    "x": "9765",
    "y": "a"
  }
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading