首页 > 解决方案 > 使用 sjson.decode() 在 NodeMCU Lua 中检测格式错误的 JSON

问题描述

在 ESP-12S 上使用 NodeMCU(最新版本)

我正在尝试解析用户提供的 JSON 并对其进行处理。但是,由于 JSON 是用户提供的,我无法保证其有效性。因此,在继续之前,我想先检查输入 JSON 是否格式错误。

正在使用以下代码:

function validatejson(input)
    
    if sjson.decode(input) then
        return true
    end

end

所以一个成功的例子是:

x = '{"hello":"world"}'

print(validatejson(x))

--> true

一个不成功的例子是:

x = '{"hello":world"}'

print(validatejson(x))

--> nil

上面的函数可以工作,但是,在我编译的代码中使用它时,它会遇到 PANIC 错误并重新启动:

 PANIC: unprotected error in call to Lua API: Incomplete JSON object passed to sjson.decode

因此,正如您可能已经做过的那样,我决定使用将pcall()错误作为布尔值返回的函数(false 表示调用中没有错误):

function validatejson(input)
    
    if not pcall(sjson.decode(input)) then
        return true
    end

end

还是没有运气!:(

任何想法如何使用 NodeMCU 在 Lua 中成功检测格式错误的 JSON?

标签: jsonluaesp8266nodemcupanic

解决方案


    if not pcall(sjson.decode(input)) then
        return true
    end

那是错误的:你只调用pcall的结果sjson.decode(input),所以错误会发生在之前pcall。这样做的正确方法是:

local ok, result = pcall(function()
   return sjson.decode(input)
end)
return ok -- might as well return result here though

推荐阅读