P
P
Pavel Chuev2017-07-26 16:13:53
JavaScript
Pavel Chuev, 2017-07-26 16:13:53

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)

I will immediately show the JSON that I receive:
{"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}}

(JSON is not all, but only the part with which I work.)
So, the problem with this line print("conditions:", data['weather'][0]['main'])
The debugger says the following about this line: attempt to index a nil value
How to fix this? After python and seasharp, I can't figure out what the problem is.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Laud, 2019-02-20
@Almazmr

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];

But this only makes sense if you get an object by the value of its field more than once. If there is only one, and it does not change, there is no way to improve if you cannot change the issue.

J
JaxxDexx, 2017-07-26
@AllDecay

In Lua, arrays are indexed from 1, not 0
print("conditions:", data['weather'][1]['main'])

S
Sergey, 2017-09-30
@Graff46

luaforge.net/projects/luajson

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question