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

Converting a huge file with a JSON document per line into a single JSON list

As you can see below I have a string and I want to convert it into standard JSON.

{"domain":"345","path":"/"}
{"domain":"5432","path":"/"}
{"domain":"345","path":"/"}
{"domain":"345","path":"/"}
{"domain":"23456","path":"/"}
{"domain":"2345","path":"/"}
{"domain":"3456","path":"/"}
{"domain":"123","path":"/"}

I have a file of 12GB which contains data exactly like this.

I want to create a new file where data is like this –

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

[
   {"domain":"345","path":"/"},
   {"domain":"5432","path":"/"},
   {"domain":"345","path":"/"},
   {"domain":"345","path":"/"},
   {"domain":"23456","path":"/"},
   {"domain":"2345","path":"/"},
   {"domain":"3456","path":"/"},
   {"domain":"123","path":"/"}
]

>Solution :

This is one of those rare special cases where it’s safe to treat JSON as raw text.

with open('out.json', 'w') as outfile, open('in.jsonl', 'r') as infile:
  outfile.write('[\n')
  for line in infile:
    outfile.write(f'  {line.rstrip()},\n')
  outfile.write(']\n')
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