Search code examples
jsonluaesp8266nodemcupanic

Detecting malformed JSON in NodeMCU Lua using sjson.decode()


Using NodeMCU (latest release) on ESP-12S

I am trying to parse user supplied JSON and do something with it. However, because the JSON is user supplied, I cannot guarantee its validity. So I want to first check if the input JSON is malformed or not, before continuing.

I was using the following code:

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

end

So a successful example would be:

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

print(validatejson(x))

--> true

and an unsuccessful example would be:

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

print(validatejson(x))

--> nil

The above function works, however, when using this in my complied code, it runs into a PANIC error and restarts:

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

So, as you'd probably have done as well, I decided to use the pcall() function which returns the error as a boolean (false means there was no error in the call):

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

end

Still no luck! :(

Any ideas how to successfully detect malformed JSON in Lua using NodeMCU?


Solution

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

    That's wrong: you're only calling pcall on the result of sjson.decode(input), so the error will happen before pcall. The correct way of doing this is:

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