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:
JavaScript
x
4
1
{"Data1": "Value1"}
2
{"Data2": "Value2"}
3
{"Data3": "Value3"}
4
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?
JavaScript
1
8
1
import json
2
3
lines = ''
4
5
with open('file.json', 'r') as f:
6
for line in f:
7
lines.append(json.loads(line))
8
Advertisement
Answer
The best way to read a JSON Lines document as a string would be to use the read()
function as follow:
JavaScript
1
3
1
with open("file.json", "r") as file:
2
data_str = file.read()
3