We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I am using a Weather Underground API to access weather data in the JSON format. I am able to parse the Key / Value pairs within the first level JSONObject eg. "moonPhase: "percentIlluminated:" but not the "sunset:" "hour:" and "minute:"as I believe "sunset:" is a JSONObject within the "moon_phase:" JSONObject.
JSON Data structure from API below...
{
"response": {
"version": "0.1",
"termsofService": "http://www.wunderground.com/weather/api/d/terms.html",
"features": {
"astronomy": 1
}
},
"moon_phase": {
"percentIlluminated": "0",
"ageOfMoon": "0",
"phaseofMoon": "New Moon",
"hemisphere": "North",
"current_time": {
"hour": "16",
"minute": "47"
},
"sunrise": {
"hour": "7",
"minute": "32"
},
"sunset": {
"hour": "17",
"minute": "23"
},
"moonrise": {
"hour": "7",
"minute": "23"
},
"moonset": {
"hour": "17",
"minute": "59"
}
},
"sun_phase": {
"sunrise": {
"hour": "7",
"minute": "32"
},
"sunset": {
"hour": "17",
"minute": "23"
}
}
}
Here is my code so far...
int moonPhase;//% illumination
int sunSet;
int sunSetHour;
int sunSetMinute;
JSONObject json;
void update_data()
{
json = loadJSONObject("http://api.wunderground.com/api/"My API Key"/astronomy/q/pws:IBRITISH423.json");
JSONObject moon_phase = json.getJSONObject("moon_phase");
moonPhase = moon_phase.getInt("percentIlluminated");
print(moon_phase);
}
void setup()
{
size(300,300);
update_data();
}
void draw()
{
//MOON PHASE
text("Moon Illumination: " + moonPhase + " %",100,80);
}
Any assistance on how to parse the sunset "Hour and Minute" values would be greatly appreciated.
Answers
in my limited understanding, JSONObject can be inside JSONObject can be inside JSONObject....
so you just need to read it out from the embedded JSONObject
Thanks for the reply and solution to my problem Chrisir. Here is my modified code below and it now works. It was the second sunset JSONObject that was tripping me up. Instead of a json.getJSONObject it needed to be a test1.getJSONObject that refers back to the main test1 - "moon_phase" object.
name test better as sunset
This code was just a simple example to be used to resolve the Object within an Object problem. I will re write from scratch using a better naming convention. Its all part of a larger project for a Weather dashboard display that will eventually be run on a Raspberry Pi. Thanks again for your help Chrisir
cheers!
remark:
the forum actually destroys urls even in code / json.
workaround in code is to say "http"+"://"+"www.................. or so
but I wonder if one could write a generic JSON sketch that would be able to read any json-file. It wouldn't rely on the names in the json-data like "sunset" but just use look up what's there....
Link
here is a json validator :
http://jsonlint.com/