Unable to get proper table key from nginx lua?

Multi tool use
Unable to get proper table key from nginx lua?
Currently posting this data:
{"test":"hello","test2":"world"}
{"test":"hello","test2":"world"}
Header is this:
"Content-Type: application/json"
"Content-Type: application/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.
table
Anyways, when I loop through it, I'm getting only one loop where the key is like this:
"test":"hello"
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
test
Here is my content_by_lua
part:
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
';
What did I do wrong here?
1 Answer
1
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"}
{"test":"hello","test2":"world"}
As a Lua table, it should be:
{"test" = "hello", "test2" = "world"}
{"test" = "hello", "test2" = "world"}
Now, why it is not properly decoding the JSON, etc. that I cannot tell from the code you have posted.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.