第二次加载JSON文件时获取“JSONDecodeError”

2024-06-12 00:59:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个脚本,它在JSON文件首次启动时加载数据,然后继续检查JSON文件是否已更新。如果已更新,则从JSON文件重新加载数据

到目前为止,初始加载工作正常,但当它再次读取文件时,我得到“json.decoder.jsondecoderror:期望值:第1行第1列(char 0)”。为什么我会犯这个错误

test.json

{"open":0}

testingFile.py

import json
import time
import datetime
import os

recordedMod = os.path.getmtime('test.json')


def getJSON():
    status = ''
    funcData = ''
    doorOpen = ''
    #read json file
    with open('test.json') as myfile:
        funcData=myfile.read()
        print(funcData)
    #load json data
    status = json.loads(funcData)
    #get Door open Status
    doorOpen = status["open"]
    #close File
    myfile.close()

    return doorOpen


doorStatus = getJSON()
print(doorStatus,end='\r')

while (True):
    currentMod = os.path.getmtime('test.json')

    if currentMod>recordedMod:
        doorStatus = getJSON()
        print(doorStatus,end='\r')

回溯

Traceback (most recent call last):
  File "testingFile.py", line 34, in <module>
    doorStatus = getJSON()
  File "testingFile.py", line 19, in getJSON
    status = json.loads(funcData)
  File "/usr/lib/python3.7/json/__init__.py", line 348, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.7/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.7/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)

更新

正在从外部源编辑和保存JSON文件。目前,我正在通过使用文本编辑器编辑JSON文件并通过ssh保存来进行测试。稍后,计划使用node.js更新文件

更新和解决方案

我接受了帮助我找到解决方案的答案,但对我遇到的问题的原因和解决方案的解释是,当文件从外部源保存时,它同时被检查。因此,文件在一瞬间是空的,这会引发错误。在没有任何形式的错误处理的情况下,这会停止代码的运行。通过在getJSON函数中添加if语句,类似于接受的答案,当文件不可用时,程序将退出函数,而不是停止

新功能

def getJSON():
    with open('test.json') as myfile:
        funcData=myfile.read()
        if funcData:
            status = json.loads(funcData)
            doorOpen = status['open']
            return doorOpen

Tags: 文件pytestjsonstatuslineopenmyfile
1条回答
网友
1楼 · 发布于 2024-06-12 00:59:59

您的程序正确地报告json文件不正确。换句话说,您最好开始相信错误消息。在这种情况下,它是一个空文件,或者至少funcData是空的

您的代码需要使用错误的输入来运行,这些输入被报告为JSONDecodeError。我不知道为什么输入文件是空的,但它是空的。程序告诉您clear as day,您可以查看funcData以验证它是否为空字符串

如果需要,函数可以只返回真/假值,如果出现任何错误,则不返回任何值。您应该处理异常,但它可以在函数内或函数外。这里我编写了一个函数来处理json文件,还有一个函数来处理显示。因为我们正在打印错误,所以我将异常处理程序放在display函数中

请注意,在json阅读器函数中,我使用“get”来处理json有效但预期数据不在其中的情况。您已经知道,如果不执行返回,所有python函数都不会返回任何值,因此如果文件为空,它将返回None而不是JSONECODERROR

我还清理了文件更改处理程序循环。它现在只执行一项任务:在文件更改时触发显示功能

import json
import os
import time

def getJsonAttribute(filename, attribute):
    with open(filename) as myfile:
        funcData = myfile.read()
        if funcData:
            status = json.loads(funcData)
            doorStatus = status.get(attribute, None)
            return bool(doorStatus)

def displayDoor(filename):
    try:
        doorStatus = getJsonAttribute(filename, 'open')
        if doorStatus is None:
            print ('what door?')
        else:
            print ('the door is', 'open' if doorStatus else 'closed')
    except json.JSONDecodeError as e:
        print ('the door has bad json:', str(e))

recordedMod = 0.0
while (True):
    currentMod = os.path.getmtime('test.json')
    if currentMod > recordedMod:
        recordedMod = currentMod
        displayDoor('test.json')
    time.sleep(1)

相关问题 更多 >