openresty/lua-cjson

"null" will be decoded as ngx.null

mike07026 opened this issue · 4 comments

local cjson = require "cjson.safe"
local r = cjson.decode("null")
ngx.say(r == ngx.null)    -- true here

I think "null" is not a valid json string, and expect decode result is nil, but r == ngx.null here.
Maybe it is better to document this behavior or just fix it in cjson source code?

I don't agree. JSON literal null has to be decoded as ngx.null, because Lua nil cannot be present in Lua tables. This is absolutely correct behavior, and consistent with null literal appearing in JSON arrays and objects (otherwise those can not be presented in Lua).

@bungle Reffer to JSON RFC4627 , " A JSON text is a serialized object or array", it means json string should be "{}" or "[]" at least . So i think "null" is not valid json string, decode should return nil in cjson.safe or throw error in cjson when the json format is invalid.

Well, this is a library, why remove possibility to decode JSON values, and only support JSON documents? You can easily test if it was a document by checking the return type of decode with type(json) == "table".

Oh, suddenly, I understand why the cjson manual says that "cjson.decode will deserialise any UTF-8 JSON string into a Lua value or table", because that cjson.decode can not only decode "full" json text, but also decode json value.
Thank you very much, @bungle