jsonluadecodelua-tableopencomputers

Lua access indeces from table generated from JSON


So, I am bound to use Lua for getting weather data from the Openweathermap API. I managed to send a http request to return and store all data but now I am stuck with a Lua table I don't know how work with. I am very new to Lua and I didn't find any guide or similar regarding such a deep nested table in Lua.

In particular I am just interested in the field called temp in main. Here is a sample response from the API: Sample request response

The dependencies are Lua's socket.http and this json to Lua table formatter. Here is my basic code structure

json = require ("json")
web = require ("socket.http")

local get = json.decode(web.request(<API Link>))

"get" now stores a table I don't know how to work with


Solution

  • After 2 days I finally found the error. I was working in a Minecraft Mod called OpenComputers which utilizes Lua. It seems like the mod uses a own version of socket.http and every time I wanted to print the response it returned two functions to use with request. I found out that if I put a "()" after the variable it returned the Response as a String and with the JSON library I could decode it into a workable table.

    Side note: I could access the weather like this: json_table["weather"]["temp"]

    The mod is pretty poorly documented on the http requests so I had to figure this out by myslef. Thanks for your responses, in the end the error was as always very unexpected!