使用 sjson.decode() 在 NodeMCU Lua 中检测格式错误的 JSON
Posted
技术标签:
【中文标题】使用 sjson.decode() 在 NodeMCU Lua 中检测格式错误的 JSON【英文标题】:Detecting malformed JSON in NodeMCU Lua using sjson.decode() 【发布时间】:2021-05-14 03:02:28 【问题描述】:在 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?
【问题讨论】:
如果你使用cjson
lua库,那么使用local cjson = require "cjson.safe"
。当使用cjson.decode()
时,它将返回nil
用于无法解析的畸形JSON 错误。这种方法将防止抛出。使用cjson.safe
,它会返回一个nil
,您可以检查它作为结果。
【参考方案1】:
if not pcall(sjson.decode(input)) then
return true
end
错了:你只是在sjson.decode(input)
的结果上调用pcall
,所以错误会在pcall
之前发生。正确的做法是:
local ok, result = pcall(function()
return sjson.decode(input)
end)
return ok -- might as well return result here though
【讨论】:
以上是关于使用 sjson.decode() 在 NodeMCU Lua 中检测格式错误的 JSON的主要内容,如果未能解决你的问题,请参考以下文章