13

I can't figure out how to create JSONL using Python3.

test = [{'a': 'b'}, {'a': 'b'}, {'a': 'b'}]

with open("data.json", 'w') as f:
    for item in test:
        json.dump(item, f)

with open("data.json") as f:
    for line in f:
        // only 1 line here! 
        print(line)

// prints
{"a": "b"}{"a": "b"}{"a": "b"}

I've tried using indent option to dump but it appears to make no different and the separators option don't seem to be a great usecase. Not sure what I'm missing here?

rix
  • 10,104
  • 14
  • 65
  • 92

1 Answers1

23

Use .write with newline \n

Ex:

import json
test = [{'a': 'b'}, {'a': 'b'}, {'a': 'b'}]

with open("data.json", 'w') as f:
    for item in test:
        f.write(json.dumps(item) + "\n")

with open("data.json") as f:
    for line in f:
        print(line)
Rakesh
  • 81,458
  • 17
  • 76
  • 113