Json – Check if value exists in Lua table

jsonlua

I am running Lua on ESP8266 Wifi module with NodeMCU firmware. My application is listening on TCP port for JSON requests. When I get the request I parse it using:

jsonRequest = json.decode(request)

So then I can access desired value with:

jsonRequest.object.state

Everything works perfectly until I send an invalid JSON (without "object"). When that happens I get this error: Lua API (attempt to index a nil value) and my program stops with execution.

MY PROBLEM: I would like to check if my table contains that key before accessing, but I can't find a way to do it.

I could do it with pairs function and loop through all keys and check if there is the right one, but that would require lots of code because I have multiple nested objects in my JSON.

Any ideas?

Best Answer

To check if the table jsonRequest contains the key "object", use:

if jsonRequest.object ~= nil then

If the values stored in the table won't be the boolean value false, you can also use:

if jsonRequest.object then
Related Topic