Using my JSON data (SOLVED)

Hi Defold Community,

Recently I have created an API for my game’s highscore system, and I’m now in the process of getting the data from the api and making it show in defold.

So far all I have used is the following code:

local function http_result(self, _, response)
	local data = json.decode(response.response)
	pprint(data)
end

function init(self)
	http.request("http://localhost:1337/highscores?_sort=score:desc&_limit=10", "GET", http_result)
end

This prints the data out just fine into the console, however I can’t seem to figure out how to make it so I can work with the data it responds with.

For instance I want to use the username and score data which it returns from JSON and set it as a gui text label.

How do I select the username or score object from the json returned?

This is the json response:

[
    {
        "username": "Dennis",
        "score": 332,
        "_id": "5bfd32af73ff7a77c0bf67f5",
        "createdAt": "2018-11-27T12:03:59.801Z",
        "updatedAt": "2018-11-27T12:03:59.893Z",
        "__v": 0,
        "id": "5bfd32af73ff7a77c0bf67f5"
    },
    {
        "username": "Robert",
        "score": 221,
        "_id": "5bfd0d3bc26cc57412869d24",
        "createdAt": "2018-11-27T09:24:11.050Z",
        "updatedAt": "2018-11-27T09:24:11.107Z",
        "__v": 0,
        "id": "5bfd0d3bc26cc57412869d24"
    },
    {
        "username": "Brian",
        "score": 220,
        "_id": "5bfd0d35c26cc57412869d23",
        "createdAt": "2018-11-27T09:24:05.214Z",
        "updatedAt": "2018-11-27T09:24:05.623Z",
        "__v": 0,
        "id": "5bfd0d35c26cc57412869d23"
    }
]

The Json you get is a lua string so put that string into:
json.decode(string) and it will return a lua table that you can use.

local function http_result(self, _, response)  
    local tbl = json.decode(response)
    pprint(tbl[2].username)  -- will print: "Robert"
end

EDIT: Misread your post a little.
I believe your problem is that you are treating the response as an jsonobject but is merely a string (response.response).
Try to use json.decode on the whole response-string first and then you can use punctuation to retrieve table elements.

4 Likes

Hi!

As @andreas.strangequest pointed out, the return of json.decode is a Lua table representation of the JSON. Also, if you want to loop over all the entries, you can do something like this:

-- looping over the users
for k, v in pairs(decoded_data) do
    print("Username " .. tostring(v.username) .. " has score: " .. tostring(v.score))
end

(Codepad link)

5 Likes

Thanks @andreas.strangequest & @sven for the quick response!

This is perfect and just what I was looking for! :grinning:

3 Likes