使用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

仍然没有成功!:(

有什么想法能够在Lua使用NodeMCU成功检测格式不正确的JSON吗?

点赞
用户4984564
用户4984564

如果只在sjson.decode(input)的结果上使用pcall,那么这是错误的,因此错误会在pcall之前发生。正确的做法是这样的:

local ok, result = pcall(function()
   return sjson.decode(input)
end)
return ok --尽管在这里还可以返回result
2021-02-10 12:35:58