We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi there! I am trying to use the openweathermap API in Processing with JSON. I have that:
JSONObject json; int temp; json = loadJSONObject("http://api.openweathermap.org/data/2.5/weather?q=London&appid=MYKEY&units=metric"); JSONObject weatherData = json.getJSONObject("main"); temp = weatherData.getInt("temp"); println(temp);
well, that is working fine but i also want to get the wheather: main (in this example "Clouds"). Here is the JSON file: { "coord":{ "lon":9.3, "lat":48.74 }, "weather":[ { "id":801, "main":"Clouds", "description":"few clouds", "icon":"02n" } ], "base":"stations", "main":{ "temp":6.38, [...] }
How I can get this data?
Answers
https://forum.Processing.org/two/discussion/15473/readme-how-to-format-code-and-text
The key entry you wanna access in order to reach the internal key "main" is the 1 below:
"weather": [ { "id": 801, "main": "Clouds", "description": "few clouds", "icon": "02n" } ],
Now the value associated to key "weather" is a JSONArray:
[ { "id": 801, "main": "Clouds", "description": "few clouds", "icon": "02n" } ]
So we use getJSONArray() for it:
JSONArray weatherArr = json.getJSONArray("weather");
Now we've reached the internal JSONObject value below:
{ "id": 801, "main": "Clouds", "description": "few clouds", "icon": "02n" }
The elements of a JSONArray are indexed by numbers starting w/
0
.Thus in order to grab the only JSONObject value inside it we invoke getJSONObject() using index
0
:JSONObject weatherObj = weatherArr.getJSONObject(0);
Finally we can grab the String "Clouds" value from key "main" w/ getString():
String weather = weatherObj.getString("main");
Here's the complete example: O:-)
You are soo awesome!! Thank you! You are very helpfull!! Dont know how I can thank u.. gj! ;)