1

It seems like this should be a simple thing. I have converted the following json structure to a lua table but I am having trouble trying to access the values inside of the array. I have looked through many questions and the internet in general and none of the examples I have tried work.

Here is the json that was converted to a lua table using cjson.decode

[{
    "user": "user_1",
    "password": "something",
    "id": "35",
    "message": "message 1"
},
{
    "user": "user_2",
    "password": "something",
    "id": "5c",
    "message": "message 2"
},
{
    "user": "user_3",
    "password": "something",
    "id": "7e",
    "message": "message 3"
},
{
    "user": "user_3",
    "password": "something",
    "id": "6f",
    "message": "message 4"
}]

I then try to access the variable like this:

ngx.say(users[0]["user"]);

However that does not work. I want to iterate the array and get out the user, password, id, and message at each index of the array but first I wanted to just see how to access the value of user at index 0 .. which should be user_1. I know this is a n00b question but any help would be greatly appreciated.

1 Answer 1

2

Lua tables start at index 1 by default.

Sign up to request clarification or add additional context in comments.

7 Comments

yeah, thought of that and tried ngx.say(users[1]["user"]); but still no joy
@JoelParker it would help if you'd provide an error message instead of just saying it does not work ;)
this is for the lua module in nginx and it just crashes, no error given
@JoelParker users[1]["user"] should work given that your json was loaded and decoded correctly. Add more code to your question.
In that case, users is an empty table, so it won't work. (users[1] is nil.)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.