Answer the question
In order to leave comments, you need to log in
How to work with JSON objects in Lua?
Greetings to all who read this. There was a need to get weather data and associate it with one game. Wrote, so far, a weather parser in Moscow (displays the current state and temperature). Actually, the code itself:
json = (loadfile "/opt/test/json.lua")()
http = require("socket.http")
function try(f, catch_f)
local status, exception = pcall(f)
if not status then
catch_f(exception)
end
end
try(function()
local res = http.request("http://api.openweathermap.org/data/2.5/weather?id=524901&units=metric&lang=en&APPID=тут api ключ")
local data = json:decode(res)
print("conditions:", data['weather'][0]['main'])
print("temp:", data['main']['temp'])
end, function(e)
print("Exception (weather):", e)
end)
{"coord":{"lon":37.62,"lat":55.75},
"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],
"base":"stations",
"main":{"temp":26.5,"pressure":1008,"humidity":44,"temp_min":25,"temp_max":27}}
print("conditions:", data['weather'][0]['main'])
attempt to index a nil value
Answer the question
In order to leave comments, you need to log in
Searching an unsorted array would require iterating over all elements (O(n)). The best thing to do here is to index this array:
// Займет O(n) времени, но только один раз
let indexedItems = {};
marketAPI.items.forEach(item => {
indexedItems[item.market_hash_name] = item;
});
// Это уже займет O(1)
let name = 'Anterior of the Abysm';
let object = indexedItems[name];
In Lua, arrays are indexed from 1, not 0print("conditions:", data['weather'][1]['main'])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question