【问题标题】:How to save and load data from JSON?如何从 JSON 中保存和加载数据?
【发布时间】:2021-01-25 08:52:03
【问题描述】:

如何从带有原始长文本数据的 JSON 文件中加载数据?

我有一个包含新闻的大文件:

[body] 是我需要分析的新闻数据。

我试着这样读:

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

但我得到一个错误:

Extra data: line 2 column 1 (char 1938)

也许你知道更好的方法,我怎样才能保存它,以便于阅读?

我使用以下代码从数据框创建了文件:

df.to_json('file.json', orient='records', lines=True)

【问题讨论】:

标签: python json python-3.x parsing


【解决方案1】:

您的数据似乎是 Newline Delimited JSON 格式。您可以使用json.loads 解析各个行,而不是尝试解析整个文件。此外,如果您使用 with 语句,则无需关闭文件。

import json

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多