【问题标题】:Unable to decode json in nginx lua?无法在 nginx lua 中解码 json?
【发布时间】:2018-12-18 00:38:13
【问题描述】:

目前通过curl发布此数据:

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

我的帖子是这样的:

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) -- decode json to lua table
                 ngx.say("Encoded: "..eJson);
                 ngx.say("Decoded: "..dJson);

编码和解码的 Json 输出:

Encoded: "{\"test2\":\"hello\",\"test3\":\"world\"}" Decoded: {"test2":"hello","test3":"world"}

我相信它应该是这样的:

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

我怎么会得到不同的输出?

【问题讨论】:

标签: json curl nginx post lua


【解决方案1】:

好的,我找到了解决方案,看来我必须再解码一次。

local dJson = cjson.decode(eJson) 
-- first decode (made it from stringified JSON into a JSON)

local d2Json = cjson.decode(dJson) 
-- second decode (made it from JSON into a table)

希望这对任何人都有帮助。

【讨论】:

    猜你喜欢
    • 2020-03-20
    • 2015-05-18
    • 2021-05-15
    • 2021-02-09
    • 2019-06-08
    • 2018-06-28
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多