无法从Nginx Lua获取正确的表密钥? [英] Unable to get proper table key from nginx lua?

查看:117
本文介绍了无法从Nginx Lua获取正确的表密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前发布此数据:

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

标题是这个:

"Content-Type: application/json"

当前正在尝试遍历json,但是在我的代码中,由于某种原因,它已经将发布的数据视为table.因此,即使我尝试对&将json解码为表格.

Currently trying to loop through the json but in my code, it already treats the posted data as table for some reason. So its useless even when I tried to encode & decode the json to table.

无论如何,当我遍历它时,我只会得到一个循环,其中的键是这样的:

Anyways, when I loop through it, I'm getting only one loop where the key is like this:

"test":"hello"

我想知道这里出了什么问题.我正在尝试遍历每个键&将该值设置为redis.

I'm wondering what went wrong here. I'm trying to loop through each key & set the value to redis.

他们的钥匙应该是这样的:

They key is supposed to be like this:

test

这是我的content_by_lua部分:

content_by_lua '
             local cjson = require "cjson"
             local redis = require "resty.redis"
             local red = redis:new()
             red:set_timeout(1000) -- 1 sec

             local ok, err = red:connect("127.0.0.1", 6379)
             if not ok then
                ngx.say("failed to connect: ", err)
                return
             end


             ngx.header.content_type = "application/json; charset=utf-8"
             ngx.req.read_body()

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

             ngx.status = ngx.HTTP_OK

             for key, val in pairs(data) do
                   ok, err = red:set(key, val)
                   if not ok then
                     ngx.say("failed to set key: ", err)
                     return
                   end
             end
           ';

我在这里做错了什么?

推荐答案

如果代码期望通过Lua表进行迭代,则它将无法处理正在测试的JSON格式的字符串:

If the code is expecting a a Lua table to iterate through, then it will not handle the JSON-formatted string that you are testing with:

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

作为Lua表,应该是:

As a Lua table, it should be:

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

现在,为什么它不能正确解码JSON等,我无法从您发布的代码中得知.

Now, why it is not properly decoding the JSON, etc. that I cannot tell from the code you have posted.

这篇关于无法从Nginx Lua获取正确的表密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆