无法在nginx lua中解码json?

当前通过curl发布此数据:

{"test2":"hello","test3":"world"}

我的POST请求如下:

curl --header "Content-Type: application/json"   --request POST   --data '{"test2":"hello","test3":"world"}'   http://localhost/test

以下是我的请求的一部分:

ngx.req.read_body()
local data = ngx.req.get_body_data()
if not data then
ngx.say("err: ",err)
 return
end

ngx.status = ngx.HTTP_OK

local eJson = cjson.encode(data)

local dJson = cjson.decode(eJson) -- 将JSON解码为Lua表

ngx.say("已编码: "..eJson);
ngx.say("已解码: "..dJson);

经编码和解码后的JSON输出:

已编码: "{\"test2\":\"hello\",\"test3\":\"world\"}" 已解码: {"test2":"hello","test3":"world"}

我认为它应该是这样的:

{"test" = "hello", "test2" = "world"}

为什么我得到不同的输出?

点赞
用户5087849
用户5087849

好的,我找到了解决方案,看起来我需要再解码一次。

local dJson = cjson.decode(eJson)
-- 第一次解码(将其从字符串化的 JSON 转换为 JSON)

local d2Json = cjson.decode(dJson)
-- 第二次解码(将其从 JSON 转换为表)

希望这可以帮助任何人。

2018-07-10 08:46:43