将字典附加到 json python 烧瓶

append dict to json python flask

由于我是编码和制作自己的小项目的新手,我终于遇到了过去几天困扰我的问题。

所以基本上我想做的是将我的字典附加到列表中,然后将其转储到 json 文件中。

    username = request.form["username"]
    password = request.form["password"]
    checkbox2 = request.form["checkbox2"]
    userDict = {

             "username" : username,
             "password" : password,
             "checkbox2" : checkbox2,
         }
print(userDict)
if os.path.exist("data.json"):
    with open("data.json", "r") as f:
        all_data = json.load(f)
else:
    all_data = []
all_data.append(userDict)
with open("data.json", "w") as f:
    json.dump(all_data, f)

这是我现在 运行 的代码。 我得到的回溯是在发送我的表格时。

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Traceback (most recent call last):

File "C:\Users\Marco\AppData\Local\Programs\Python\Python36-32\lib\site- 
packages\flask\app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)

File "C:\Users\Marco\AppData\Local\Programs\Python\Python36-32\lib\site- 
packages\flask\app.py", line 2295, in wsgi_app
response = self.handle_exception(e)

File "C:\Users\Marco\AppData\Local\Programs\Python\Python36-32\lib\site- 
packages\flask\app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)

File "C:\Users\Marco\AppData\Local\Programs\Python\Python36-32\lib\site- 
packages\flask\_compat.py", line 35, in reraise
raise value

File "C:\Users\Marco\AppData\Local\Programs\Python\Python36-32\lib\site- 
packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()

File "C:\Users\Marco\AppData\Local\Programs\Python\Python36-32\lib\site- 
packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)

File "C:\Users\Marco\AppData\Local\Programs\Python\Python36-32\lib\site- 
packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)

File "C:\Users\Marco\AppData\Local\Programs\Python\Python36-32\lib\site- 
packages\flask\_compat.py", line 35, in reraise
raise value

File "C:\Users\Marco\AppData\Local\Programs\Python\Python36-32\lib\site- 
packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()

File "C:\Users\Marco\AppData\Local\Programs\Python\Python36-32\lib\site- 
packages\flask\app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)

File "C:\Users\Marco\Desktop\test\server.py", line 28, in sendinfo
all_data = json.load(f)

File "C:\Users\Marco\AppData\Local\Programs\Python\Python36- 
32\lib\json\__init__.py", line 299, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)

File "C:\Users\Marco\AppData\Local\Programs\Python\Python36- 
32\lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)

File "C:\Users\Marco\AppData\Local\Programs\Python\Python36- 
32\lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())

File "C:\Users\Marco\AppData\Local\Programs\Python\Python36- 
32\lib\json\decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

如果 data.json 为空,我预期的 json 输出如下

  {
  "all_data": [{
      "username": "test",
      "password": "test2",
      "checkbox2": "on"

  }]
}

如果文件确实有 "all_data": 在文件中,那么我的预期输出应该是

    {
  "all_data": [{
          "username": "test",
          "password": "test2",
          "checkbox2": "on"
      },
      {
          "username": "test3",
          "password": "test4",
          "checkbox2": "on"
      }
  ]
}

这个问题已经困扰我 3 天了,我认为这是我最后的选择,因为我是那种想自己解决的人。

提前致谢。

您的 data.json 是否已存在但为空? JSON 库在这种情况下会抛出错误!您应该在 data.json 中填写 [] 之类的字符串以避免此错误。

正如 Rishav 所指出的,当文件 data.json 存在但为空时,错误来自 json.load(f) 中的语句:

    if os.path.exist("data.json"):
        with open("data.json", "r") as f:
            all_data = json.load(f)

您可以通过不仅检查文件是否存在而且检查文件是否为空来修复此问题,如下所示:

    if os.path.exist("data.json") and os.path.getsize("data.json") > 0:
        with open("data.json", "r") as f:
            all_data = json.load(f)

那么您的代码应该会按预期工作。