我如何在python Json中停止此解码错误

时间:2019-01-11 01:49:58

标签: python json decode

我正在用python json进行练习,我制作了一个函数来打开一个文件,并加载存储在该文件中的数字,但是如果该文件不存在,它将排除错误,并要求输入喜欢的文件号,然后将该号转储到文件中,然后加载。但我不断收到错误消息

import json

def get_num():
    filename = 'numberssfresdfs.json'
    try:
        with open(filename) as num:
            number = json.load(num)
    except FileNotFoundError:
        favorite_num = input("Please enter your favorite number ")
        with open(filename, 'w') as num:
            json.dump(favorite_num, num)
            print("Your favorite number is " )
    else:
        print("I know your favorite number, its " + str(number))

get_num()

我不断收到此错误

Traceback (most recent call last):
File "remember_favorite_num.py", line 16, in <module>
  get_num()
File "remember_favorite_num.py", line 7, in get_num
  number = json.load(num)
File "C:\Users\kenda\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\kenda\AppData\Local\Programs\Python\Python36- 
  32\lib\json\__init__.py", line 354, in loads
  return _default_decoder.decode(s)
File "C:\Users\kenda\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\kenda\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)

1 个答案:

答案 0 :(得分:0)

您永远都不会到达except块中的代码,因为numberssfresdfs.json确实存在。

您收到json.load错误消息,因为numberssfresdfs.json不包含有效的json或为空。

您可以使用json linter(one online linter)来验证您的文件包含有效的json。

一旦确认您正在使用有效的json,就可以完成其余的逻辑。