如何解决在Python中使用json文件时出错
帮助解决json错误-
C:\Users\123\AppData\Local\Programs\Python\Python38>python C:\main_3.py
Traceback (most recent call last):
File "C:\main_3.py",line 10,in <module>
data = json.load(file)
File "C:\Users\123\AppData\Local\Programs\Python\Python38\lib\json\__init__.py",line 293,in load
return loads(fp.read(),File "C:\Users\123\AppData\Local\Programs\Python\Python38\lib\json\__init__.py",line 357,in loads
return _default_decoder.decode(s)
File "C:\Users\123\AppData\Local\Programs\Python\Python38\lib\json\decoder.py",line 337,in decode
obj,end = self.raw_decode(s,idx=_w(s,0).end())
File "C:\Users\123\AppData\Local\Programs\Python\Python38\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)
C:\Users\123\AppData\Local\Programs\Python\Python38>
也许此错误是由于文件为空-ping_data.json?在这种情况下,我不知道如何为首次启动准备该文件。
电报机器人。 该程序的目的是对主机执行ping操作并记录上次检查的状态,并且在程序崩溃和启动的情况下,必须从文件中读取上次检查的所有结果。
完整代码
import telebot
from pythonping import ping
import time
import yaml
from libs.host import address
import json
ping_data = dict()
with open('C:\ping_data.json') as file:
data = json.load(file)
def init():
global bot,userid,interval
interval = 30
with open('C:\config2.yaml',encoding="utf-8") as f:
try:
docs = yaml.load_all(f,Loader=yaml.FullLoader)
for doc in docs:
for k,v in doc.items():
if k == "botkey":
bot = telebot.TeleBot(v)
elif k == "userid":
userid = v
elif k == "hosts":
set_hosts(v)
elif k == "interval":
interval = int(v)
except yaml.YAMLError as exc:
print(exc)
def set_hosts(hosts):
"""
Здесь парсим список хостов и передаем их в массив
"""
global hosts_list
hosts_list = []
for item in hosts:
ac = item.split(":")
hosts_list.append(address(ac[0],ac[1]))
def send_message(message):
"""
Посылаем сообщение пользователю
"""
bot.send_message(userid,message)
def ping_host(address):
status = ping_url(address.address)
if data['address.address'] != status:
ping_data['address.address'] = status
send_message(( "! " if status is None else "+ " if status else "- ") + address.comment)
def ping_url(url):
"""
Пинг хоста. Response list - это ответ библиотеки ping. По умолчанию она
посылает четыре пакета. Если хотя бы один пинг успешен,хост активен
"""
try:
response_list = ping(url,timeout=5,verbose = True)
except:
return None
return sum(1 for x in response_list if x.success) > 0
def main():
"""
Бесконечный цикл,который пингует сервисы один за другим.
"""
init()
while True:
for host in hosts_list:
ping_host(host)
with open('C:\ping_data.json','w') as file:
json.dump(ping_data,file,indent=2)
time.sleep(interval)
if __name__ == '__main__':
main()
例如config2.yaml文件的内容。
botkey: ***********************************
userid: -**********
interval: 60
hosts:
- "google.com:Google.ru"
- "ya.ru:Yandex.ru"
- "mail.ru:Mail.ru"
- "rambler.ru:Rambler.ru"
解决方法
您不能将空文件读为词典。但是您可以从文件中读取空字典。
所以, 尝试将空字典保存在文件中,而不是在首次启动时保存文件 即:ping_data.json的内容应为空花括号(如以下内容所示)
{}
干杯。
,了解,一切正常。该错误仅是由于JSON文件的编码引起的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。