如何在lua nginx中解码json字符串?

我有以下nginx配置文件:

worker_processes  1;
error_log logs/error.log;
events {
    worker_connections 1024;
}
http {
    init_by_lua 'cjson = require("cjson")';
    server {
        listen 8080;

        location / {
        default_type text/html;
        content_by_lua '
            json_text = "{ \"aaa\": \"bar\" }"
            local message = cjson.decode(json_text)
            ngx.say(message)
        ';
        }

    }
}

当我访问网址http://localhost:8080时,我收到以下错误消息:

content_by_lua(nginx.conf:17): in main chunk, client: 127.0.0.1, server: , request: "GET / HTTP/1.1", host: "localhost:8080"
2019/11/25 15:03:12 [error] 36979#684497: *2 lua entry thread aborted: runtime error: content_by_lua(nginx.conf:17):2: attempt to call global 'aaa' (a nil value)

它抱怨调用全局'aaa',但我要做的只是解码json字符串。我的脚本错了吗?

点赞
用户4984564
用户4984564

请不要使用 content_by_lua,即使 手册 告诉你要使用 content_by_lua_block。你遇到的问题可能是由于字符串引号问题引起的,可能是因为 nginx 已经解释了 \,而 Lua 得到的是未转义的 "

另外,如果你要在字符串中使用引号,最好使用 [[]],甚至可以加一些 =

        content_by_lua_block {
            json_text = [[{ "aaa": "bar" }]]
            local message = cjson.decode(json_text)
            -- 与以下代码等效:
            -- local  message = {aaa = "bar"}
            ngx.say(message)
        }

然而,你的代码无论如何都不会工作,因为 cjson.decode 返回表格,而 ngx.say 不会将其打印出来(它只会打印字符串和数组),因此你不会得到任何输出。你可以打印 message.aaa,例如,这将向用户输出 _bar_。

2019-11-25 07:10:17