lua cjson encode nil field

712 Views Asked by At

I have a lua table such as:

local _table = {}

_table["name"] = "some user name"    
_table["phone"] = nil

ngx.say(cjson.encode(_table))

The ngx.say output as below:

{"name":"some user name"}

As you can see the phone field in _table has been ignored! How to set encoding-options to include any nil field during cjson encode processing. Such as:

{"name":"some user name", "phone": null}
1

There are 1 best solutions below

0
On BEST ANSWER

Assigning nil to a table field means that this table field will be treated as unset, i.e. from Lua's point of view it stops existing. CJSON comes with a dedicated value to represent null, use that instead:

_table["phone"] = cjson.null