json.decode a table with arrays as values

Dear Corona-community,

I have been struggling with this for hours: My server sends the following json string:

{“votes1”: {32, 22, 27, 44}, “votes2”: {“empty”}}

So, keys are “votes1” and “votes2” and values are arrays holding either the string “empty” or numbers. Unfortunately json.decode returns nil. I tried all kinds of combinations:

{“votes1”: “{32, 22}”, “votes2”: “{“empty”}”}

{votes1: {32, 22}, votes2: {“empty”}}

but with no success. What I’d like to do:

Server returns two arrays: One array “votes1” with userIDs and another array “votes2” with userIDs. If there are no userIDs for a specific condition, the array should be empty, or hold “empty” as a string or whatever.

On clientside I’d like to loop through all the “votes1” userIDs, then loop through all the “votes2” userIDs.

My head is going crazy right now, hope it gets clear where the problem is.

Any ideas?

Thanks :slight_smile:

You need to change the structure of your json data so that it uses square brackets for the arrays:

{"votes1": [32, 22, 27, 44], "votes2": ["empty"]}

When I decoded your original json string I also got nil. So I worked backwards and made the lua table first, encoded that, and then looked at the resulting json string:

local desiredTable = { votes1 = {32, 22, 27, 44}, votes2 = {"empty"} } print(json.encode(desiredTable))

You are my hero :slight_smile:

Thanks, works like a charme!

You need to change the structure of your json data so that it uses square brackets for the arrays:

{"votes1": [32, 22, 27, 44], "votes2": ["empty"]}

When I decoded your original json string I also got nil. So I worked backwards and made the lua table first, encoded that, and then looked at the resulting json string:

local desiredTable = { votes1 = {32, 22, 27, 44}, votes2 = {"empty"} } print(json.encode(desiredTable))

You are my hero :slight_smile:

Thanks, works like a charme!