Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

python - How to save and load data from JSON?

How can I load data from JSON file with raw long text data?

I have big file with news:

[body] is a news data that I need to analyze.

I tried to read it like this:

with open('file.json', 'r') as openfile: 
  
    # Reading from json file 
    dfnew = json.load(openfile) 
openfile.close

But I get an error:

Extra data: line 2 column 1 (char 1938)

Maybe you know the better way, how can I save it, to easily read?

I created the file from dataframe by using this code:

df.to_json('file.json', orient='records', lines=True)
question from:https://stackoverflow.com/questions/65881546/how-to-save-and-load-data-from-json

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your data seems to be in the Newline Delimited JSON format. Instead of trying to parse the whole file, you can parse the individual lines with json.loads. Also you don't need to close files if you are using a with statement.

import json

with open('file.json') as openfile:
    for line in openfile:
        dfnew = json.loads(line)
        print(dfnew)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...