Printing value from a lua table made from json

Ok given up and coming for help :smiley: , been googling and trying all sorts of examples but none seem to be working hopefully one of you fine people can help me out :slight_smile:

I’m totally new to lua, only used to PHP

So far ive created a “http.request” which returns a json string, just a basic one for now like the following

{"scores":[{"John":"200"},{"Steve":"50"}]}

which is then decoded using “json.decode”

which works fine, and when printed to console prints out the following

“DEBUG:SCRIPT: table: 0x01f75821d740”

So I assume the json is now turned into a lua table as it mentions in the docs? however no matter what I try and all the examples ive tried none seem to print anything from the table.

if possible I would like to print any row from the table, or a way to loop through the table would be find and I can just grab the rows that way by a counter or something.

however anytime I try and print anything from the table it just says “nil”

thanks in advance ill carry on trying other stuff in the mean time and post back if I fix it

You can use pprint() to print the whole table in one go:

pprint(decoded_json)

or access individual elements:

local scores = decoded_json.scores
local first_score = scores[1]
pprint(first_score)

or iterate over everything (non-recursively):

for key, value in pairs(decoded_json) do
    print(key, "=", value)
end

I would recommend a data structure more like:

{"scores":[{"name":"John","score":200},{"name":"Steve","score":50}]}

so that all the score objects have the same keys, just with different values. That lets you do:

for _, score in ipairs(decoded_json.scores) do
    print(score.name, "got", score.score, "points")
end
3 Likes
{"scores":[{"name":"John","score":200},{"name":"Steve","score":50}]}

I had tried a few of those first exmaples and didnt seem to work, however your last example works PERFECT and is exactly what I wanted, thanks a lot :slight_smile: , works great much apprietated

2 Likes