如何解决使用 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?
解决方法
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。