Home > Net >  Text file to JSON
Text file to JSON

Time:11-15

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:

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.

CodePudding user response:

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"
  }
]
  • Related