python - json.decoder.JSONDecodeError : Expecting ',' delimiter: line 1 column 21641 (char 21640)

标签 python json python-3.x

调用函数时出现标题所述的错误:

def read_file(file_name):
    """Return all the followers of a user."""
    f = open(file_name, 'r')
    data = []
    for line in f:
        data.append(json.loads(line.strip()))
    f.close()
    return data

示例数据如下所示:

"from": {"name": "Ronaldo Naz\u00e1rio", "id": "618977411494412"}, 
"message": "The king of football. Happy birthday, Pel\u00e9!", 
"type": "photo", "shares": {"count": 2585}, "created_time": "2018-10-23T11:43:49+0000", 
"link": "https://www.facebook.com/ronaldo/photos/a.661211307271022/2095750393817099/?type=3", 
"status_type": "added_photos", 
"reactions": {"data": [], "summary": {"total_count": 51779, "viewer_reaction": "NONE"}}, 
"comments": {"data": [{"created_time": "2018-10-23T11:51:57+0000", ... }]}

最佳答案

您尝试将文件的每一行单独解析为 JSON,这可能是错误的。您应该读取整个文件并立即转换为 JSON,最好使用 with,这样即使发生异常,Python 也可以处理文件的打开和关闭。

由于 json.load 接受文件对象并自行处理其读取,整个事情可以压缩为 2 行。

def read_file(file_name):
    with open(file_name) as f:
        return json.load(f)

关于python - json.decoder.JSONDecodeError : Expecting ',' delimiter: line 1 column 21641 (char 21640),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53047283/

相关文章:

php - 从 XML 响应中提取某些值以创建自定义 JSON 数组

json - 使用 bash 从 JSON 文件中提取数据

python - 将字符串列表转换为函数调用

python - 如何在 python 类的 init 中自动设置 self 属性?

python - 为什么 Python 字符串连接适用于俄语文本,但 string.format() 不起作用

python - 使 tkinter 窗口出现在任务栏中

java - 如何访问 JsonPropertyOrder

python - 我应该使用 Python casefold 吗?

python - 大于 256 小于 -5 的整数缓存

python - scikit-learn 中带有 LeaveOneOut 的 roc_auc 评分方法