Getting error " attempt to index nil with 'main' " when trying to print out JSON data

Im trying to get weather data from the openweathermap API, but I get this error when I try to fetch the weather from it

http = game.HttpService
link = "http://api.openweathermap.org/data/2.5/weather?q=Texas&appid={insert api key here}"
data = http:GetAsync(link)
data = http:JSONDecode(data)

local weather = http:JSONEncode(data)
print(tostring(weather[1].main))

I get this error in the console:

13:59:37.305  Workspace.Script:7: attempt to index nil with 'main'  -  Server - Script:7

JSON data from openweathermap

{"coord":{"lon":-99.2506,"lat":31.2504},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"base":"stations","main":{"temp":284.15,"feels_like":280.93,"temp_min":284.15,"temp_max":284.15,"pressure":1013,"humidity":43},"visibility":10000,"wind":{"speed":1.54,"deg":80},"clouds":{"all":1},"dt":1611675761,"sys":{"type":1,"id":3395,"country":"US","sunrise":1611667945,"sunset":1611705994},"timezone":-21600,"id":4736286,"name":"Texas","cod":200}

I’m sorry if my code looks bad, I couldn’t find any tutorials that go past the basics of JSONDecode and EncodeUrl()

Can you replace weather[1] with something else? Since weather[1] doesn’t exist.

I’m not sure what I can replace it with, I tried doing

local weather = weather.weather.main
--This returns the same error
local weather = weather.main
--This prints out nil

To debug, try:

for i,v in pairs(weather) do
print(v)
end

Why are you reencoding the data after decoding it a second ago. If you want to access it via a script you should keep it decoded

try doing
print(data.weather.main) and removing the weather variable all together

For some reason I messed up some code earlier that made it print out hexadecimals(?) and thought that I needed to re-encode it. I tried

print(data.weather.main)

but it printed out nil

ok how about print(data.weather[1].main) and print(data.weather[0].main)

1 Like

It works! (data.weather[1].main) Thanks!