Home > database >  Read JSON Lines file as String in Python
Read JSON Lines file as String in Python

Time:01-06

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

CodePudding user response:

You can simply use f.read() if you aren't worried about the memory usage in case of large files or else your implementation seems fine, except the part which you are trying to use append() with string. This can be achieved through simple modification

lines = ""
with open("links.jl", "r") as f:
    for line in f:
        lines  = line

CodePudding user response:

you can use following template to load your JSON string into the DataFram

import pandas as pd
df = pd.read_json (r'C:\Users\Ron\Desktop\data.json')
print (df)
  •  Tags:  
  • Related