【问题标题】:How can I decode a json string in lua nginx?如何在 lua nginx 中解码 json 字符串?
【发布时间】:2020-03-20 08:22:46
【问题描述】:

我有如下的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)
        ';
        }

    }
}

当我访问 url 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)

它抱怨调用 global 'aaa' 但我正在做的只是解码一个 json 字符串。我在脚本中有什么错误吗?

【问题讨论】:

    标签: nginx lua


    【解决方案1】:

    请不要使用content_by_lua;甚至manual 告诉您改用content_by_lua_block。您的问题很可能是由于错误地引用了字符串引起的;可能是因为 nginx 已经解释了 \ 而 Lua 只是得到了一个未转义的 "

    另外,如果您要在字符串中使用引号,最好保持安全并使用[[]],甚至在其中添加一些=s。

            content_by_lua_block {
                json_text = [[{ "aaa": "bar" }]]
                local message = cjson.decode(json_text)
                -- Equivalent to:
                -- local  message = {aaa = "bar"}
                ngx.say(message)
            }
    

    你的代码无论如何都不会工作,因为cjson.decode 返回一个表,ngx.say 不会打印(它只打印字符串和数组),所以你不会得到任何输出。例如,您可以打印message.aaa,它将向用户打印bar

    【讨论】:

      猜你喜欢
      • 2018-06-28
      • 2018-12-18
      • 2021-12-28
      • 1970-01-01
      • 2011-08-27
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      • 2019-07-26
      相关资源
      最近更新 更多