简体   繁体   English

JSON 使用 try 和 except 的错误检查不起作用

[英]JSON error checking using try and except doesn't work

I am calling an API every 5 minutes to download data but there are some occasions when the correct JSON file is not returned.我每 5 分钟调用一次 API 来下载数据,但有时不会返回正确的 JSON 文件。 In these cases I want to use the previous dataset as a substitute.在这些情况下,我想使用以前的数据集作为替代。 I have the following code that runs but I still get missed data.我运行了以下代码,但仍然丢失了数据。

with open(r'C:\Users\david\GrowattAPI\plantData.json', 'r+') as file:
    try:
        shutil.copyfile(r'C:\Users\david\GrowattAPI\plantData.json',
                        r'C:\Users\david\GrowattAPI\plantData_old.json')
        data = json.load(file)
        file.close()
    except:
        shutil.copyfile(r'C:\Users\david\GrowattAPI\plantData.json',
                        r'C:\Users\david\GrowattAPI\plantData_error.json')
        file.close()
        f = open(r'C:\Users\david\GrowattAPI\plantData_old.json')
        data = json.load(f)
        f.close()

There has never been any error file written to indicate missed data but there are gaps.从来没有写入任何错误文件来指示丢失的数据,但存在差距。 I am thinking that the except code never executes.我在想except代码永远不会执行。 I have seen JSON file return with just {} .我看到 JSON 文件只返回{}

I have tried json.decoder.JSONDecodeError , ValueError , and IndexError individually and as a combination.我已经单独或组合尝试json.decoder.JSONDecodeErrorValueErrorIndexError

Is there a way to capture all exceptions and just use the previous dataset?有没有办法捕获所有异常并只使用以前的数据集?

Update更新

I have done some more investigating by capturing 24 hours of 5 minute data.我通过捕获 24 小时 5 分钟的数据做了更多调查。 From 288 returns, 7 of the JSON files had issues, 4 of the them were {} and the balance had a subset of standard JSON file that is returned.从 288 次返回中,JSON 文件中有 7 个有问题,其中 4 个是{} ,其余的返回了标准 JSON 文件的子集。 This is a consistent problem every day.这是每天都会出现的问题。 I only want 6 data points out of the JSON file that has 335 lines in it.我只想要包含 335 行的 JSON 文件中的 6 个数据点。 The data I pick up is nested to 5 levels.我提取的数据嵌套了 5 层。 I reference it as follows我参考如下

SolarGeneration = data['332761']['devices']['NTCIA13017']['statusData']['ppv']
Voltage = data['332761']['devices']['NTCIA13017']['statusData']['vac1']
BatteryDischarge = data['332761']['devices']['NTCIA13017']['statusData']['pdisCharge1']
BatteryCharge = data['332761']['devices']['NTCIA13017']['statusData']['chargePower']
Consumption = data['332761']['devices']['NTCIA13017']['statusData']['pLocalLoad']
SOC = data['332761']['devices']['NTCIA13017']['statusData']['SOC']

I am now trying to use jsonschema to see if the tags of the 6 data points I want are contained in the JSON file that is returned.我现在正在尝试使用jsonschema查看我想要的6个数据点的标签是否包含在返回的JSON文件中。

import json
from jsonschema import validate

def validateJson(data):
 try:
    validate(instance=data, schema=good_schema)
 except jsonschema.exceptions.ValidationError as err:
    return False
 return True

# schema to check against
good_schema = {
 "type": "object",
 "properties": {
     "vac1": {"type": "number"},
     "SOC": {"type": "number"},
     "pdisCharge1": {"type": "number"},
     "ppv": {"type": "number"},
     "pLocalLoad": {"type": "number"},
     "chargePower": {"type": "number"},
 },
}

f = open(r'C:\Users\david\PycharmProjects\JSON_TEST\2110.json')
data = json.load(f)
isValid = validateJson(data)
if isValid:
    print(data)
    print("Given JSON data is Valid")
else:
    print(data)
    print("Given JSON data is InValid")

Even when I load an empty file {} the code returns a valid TRUE.即使当我加载空文件{}时,代码也会返回有效的 TRUE。

Any ideas?有任何想法吗?

You can use the Exception class as an argument to your except statement.您可以使用Exception class 作为except语句的参数。

There's a similar solution here:这里有一个类似的解决方案:

How can I write a `try`/`except` block that catches all exceptions? 如何编写捕获所有异常的 `try`/`except` 块?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM