Search code examples
python-3.xjsonlines

Create JSONL with Python


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?


Solution

  • 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)