1

I have file (around 6 GB) that each line is JSON.

{"name":"name1", "age":40, "car":null}
{"name":"name2", "age":30, "car":null}
{"name":"name3", "age":30, "car":null}

How can I convert it into a JSON array with Python?

martineau
  • 119,623
  • 25
  • 170
  • 301
yokjc232
  • 91
  • 5

2 Answers2

1
import fileinput
for line in fileinput.input("test.txt", inplace=True):
    if 1 != fileinput.filelineno():
        print(',{}'.format(line), end='')
    else:
        print('[{}'.format(line), end='')
open("test.txt","a").write(']')
     
MicrosoctCprog
  • 460
  • 1
  • 3
  • 23
0

Load each line and save it into a list.

with open('file.txt', 'r') as in_file:
    lines = [json.loads(line) for line in in_file.readlines()]

Then you can save that to a file like with json.dump()

with open('out.json', 'w') as out_file:
    json.dump(lines, out_file)
Fynngin
  • 9
  • 3