Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Function to parse JSON response
- local function parseJson(jsonString)
- local obj = {}
- local stack = {}
- local curr = obj
- local key
- local inString = false
- local stringValue = ""
- for i = 1, #jsonString do
- local c = jsonString:sub(i, i)
- if c == "{" and not inString then
- local newTable = {}
- if key then
- curr[key] = newTable
- table.insert(stack, curr)
- curr = newTable
- else
- table.insert(stack, curr)
- curr = newTable
- end
- key = nil
- elseif c == "}" and not inString then
- curr = table.remove(stack)
- elseif c == "\"" then
- inString = not inString
- elseif c == ":" and not inString then
- key = stringValue
- stringValue = ""
- elseif c == "," and not inString then
- if key then
- curr[key] = stringValue
- key = nil
- else
- table.insert(curr, stringValue)
- end
- stringValue = ""
- else
- stringValue = stringValue .. c
- end
- end
- return obj
- end
- -- Function to URL encode a string
- local function urlEncode(str)
- if str then
- str = string.gsub(str, "([^%w ])", function(c)
- return string.format("%%%02X", string.byte(c))
- end)
- str = string.gsub(str, " ", "+")
- end
- return str
- end
- -- Function to fetch weather data from the API
- local function fetchWeatherData(city)
- local apiKey = "771196291bcb63791f108494bc9ce166" -- Your API key here
- local encodedCity = urlEncode(city)
- local apiUrl = "http://api.openweathermap.org/data/2.5/weather?q=" .. encodedCity .. "&appid=" .. apiKey
- local response = ""
- local request = http.get(apiUrl)
- if request then
- response = request.readAll()
- request.close()
- else
- print("Failed to fetch weather data from the API")
- end
- return response
- end
- -- Function to display weather data
- local function displayWeather(weatherData)
- if weatherData and weatherData.main then
- print("Weather Data:")
- print("City: " .. (weatherData.name or "Unknown"))
- print("Temperature: " .. (weatherData.main.temp and (weatherData.main.temp .. "°C") or "N/A"))
- print("Humidity: " .. (weatherData.main.humidity and (weatherData.main.humidity .. "%") or "N/A"))
- print("Wind Speed: " .. (weatherData.wind and weatherData.wind.speed and (weatherData.wind.speed .. " m/s") or "N/A"))
- else
- print("Failed to fetch weather data.")
- end
- end
- -- Main function
- local function main()
- print("Enter a city name:")
- local city = read()
- local weatherDataResponse = fetchWeatherData(city)
- if not weatherDataResponse then
- return
- end
- local parsedData = parseJson(weatherDataResponse)
- displayWeather(parsedData)
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement