首页 > 解决方案 > 如何读取然后更新 json 文件?

问题描述

我需要能够json在 python 中更新文件。我可以让它json第一次创建并写入文件,但它一直告诉我我有一个json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0).

这是代码:

import pathlib
import json

obj = {
        "a": "1",
        "b": "2",
        "c": "3"
    }
obj2 = {
        "d": "4",
        "e": "5",
        "f": "6"
    }


jsonFile = pathlib.Path("jsonFile.json")
if jsonFile.exists() == False:
    with open("jsonFile.json", "w") as savefile:
        dumpJSON = json.dump(obj, savefile)
else:
    with open("jsonFile.json", "w+") as savefile:
        readObj = json.load(savefile)
        readObj.update(obj2)
        dumpJSON = json.dump(readObj, savefile)

这是完整的追溯。

Traceback (most recent call last):
  File "h:\Projects\Programs\Calculator\stackQuestion.py", line 22, in <module>
    readObj = json.load(savefile)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

我正在使用Python 3.9.2.
我搜索了以下站点:
使用 Python 读取、写入和解析 JSON
Python-json.load 和 json.loads 之间的区别使用 Python JSONDecodeError: 预期值:第 1 行第 1 列 (char 0)
附加到 JSON 文件我该怎么做将 JSON 数据写入文件?Python JSON AttributeError:“str”对象没有属性“read”


标签: pythonjson

解决方案


您不能使用相同的 with 子句读取和写入 json 文件。请使用此代码消除读取和写入缓冲区的错误,该错误不允许您在读取时写入

import pathlib
import json
import os

obj = {
        "a": "1",
        "b": "2",
        "c": "3"
    }
obj2 = {
        "d": "4",
        "e": "5",
        "f": "6"
    }


jsonFile = "jsonFile1.json"

print(obj)
if os.path.exists(jsonFile) == False:
    print("1123")
    with open(jsonFile, "w") as savefile:
        json.dump(obj, savefile)
else:
    with open(jsonFile, "r") as json_file:
        readObj = json.load(json_file)
        readObj.update(obj2)
        print(readObj)
        
        
    with open(jsonFile, "w") as json_file:
        json.dump(readObj, json_file)

推荐阅读