json - 使用 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
推荐阅读
- c - 从通过引用传递的数组变量中获取第一个元素
- ruby - Sinatra App 获取请求未连接到子目录视图
- java - 为什么我的 getter 和 setter 不能与 string.length() 一起使用?
- sql - 计算具有空值的最近连续行数
- jquery - 循环遍历表数据并使用 jQuery 获取数据
- scala - 从依赖类型问题的 HList 中的 Scala 无形选择
- powerbi - DAX 查询返回 1 个月前的文本值
- salesforce - 我正在学习 Apex 代码中的面向对象概念,并且不断收到 "Variable does not exist: name" 。我究竟做错了什么?
- c# - 如何在 Entity Framework Core 中设置多个一对一关系?
- scala - 假/真列常数