将dict附加到json python flask

时间:2018-06-02 21:56:05

标签: python json flask jsonlint

作为编码和制作我自己的小项目的新手,我终于遇到了一个问题,这个问题在过去的几天里一直困扰着我。

所以基本上我想做的就是将我的dict附加到列表中,然后将其转储到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)

这是我目前正在运行的代码。 我得到的Traceback是在发送表格时。

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"

  }]
}

如果文件中已经有#34; all_data":那么我的预期输出应该是

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

这个问题困扰了我3天,我认为这将是我的最后一招,因为我是那种想自己解决问题的人。

提前致谢。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

正如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)

然后您的代码应按预期工作。