Using openweathermap API

edited October 2016 in Questions about Code

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

  • edited October 2016 Answer ✓

    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:-)

    // forum.Processing.org/two/discussion/18543/using-openweathermap-api  
    // GoToLoop (2016-Oct-14)
    
    final String JSON =
      "{ " +
      "'coord': { 'lon': 9.3, 'lat': 48.74 }, " +
      "'weather': " +
      "[{ " +
      "'id': 801, " +
      "'main': 'Clouds', " +
      "'description': 'few clouds', " +
      "'icon': '02n'" +
      " }], " +
      "'base': 'stations', " +
      "'main': { 'temp': 6.38 }" +
      " }";
    
    JSONObject json = parseJSONObject(JSON);
    println("JSON:\n" + json, ENTER);
    
    JSONArray weatherArr = json.getJSONArray("weather");
    println("Weather Array:\n" + weatherArr, ENTER);
    
    JSONObject weatherObj = weatherArr.getJSONObject(0);
    println("Weather Object:\n" + weatherObj, ENTER);
    
    String weather = weatherObj.getString("main");
    println("Weather:", weather);
    
    exit();
    
  • You are soo awesome!! Thank you! You are very helpfull!! Dont know how I can thank u.. gj! ;)

Sign In or Register to comment.