Search code examples
pythonjsonjsonlines

Read JSON Lines file as String in Python


I have a JSON Lines file that I would like to read as a string in Python. The file contains multiple JSON objects in this format:

{"Data1": "Value1"}
{"Data2": "Value2"}
{"Data3": "Value3"}

I tried the following code in Python but it returned an error. I was able to load the file as a list of dictionaries using lines = [] but apprently it doesn't work for a string. How can I read the whole file as a string?

import json

lines = ''

with open('file.json', 'r') as f:
    for line in f:
        lines.append(json.loads(line))

Solution

  • The best way to read a JSON Lines document as a string would be to use the read() function as follow:

    with open("file.json", "r") as file:
        data_str = file.read()