I’m trying to figure out how to use an http get to pull json data and then use one of the returned values. From what I’ve been able to determine so far you have to do it via a lambda function. My goal is to return a simple decimal number from the following json example.
{
"queryCost": 1,
"latitude": 42.0333,
"longitude": -91.5996,
"resolvedAddress": "Marion, IA, United States",
"address": "Marion,IA",
"timezone": "America/Chicago",
"tzoffset": -5,
"days": [
{
"datetime": "2021-10-16",
"sunrise": "07:20:23",
"sunset": "18:22:43",
"moonphase": 0.42
}
]
}
The attribute I’m trying to get is “moonphase”.
I found someone else trying something similar ESPhome how to read json from web? - ESPHome - Home Assistant Community (home-assistant.io), however I’ve been unable to duplicate it. I’ve also been reading over the documentation for v5 of arduinojson, but that doesn’t seem to want to work either. Below is what I’ve got so far.
sensor:
- platform: template
name: "Moon Coverage"
id: moon_coverage
time:
- platform: sntp
id: sntp_time
timezone: America/Chicago
on_time:
- seconds: 0
minutes: /1
then:
- lambda: |-
HTTPClient http;
http.begin("https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/Marion%2CIA/today?unitGroup=us&key=redacted&include=days&elements=datetime,moonphase,sunrise,sunset");
http.GET();
DynamicJsonBuffer jsonBuffer(31000);
JsonObject& root = jsonBuffer.parseObject(http.getStream());
double moonphase = root["days"]["moonphase"];
id(moon_coverage).publish_state(moonphase);
ESP_LOGD("main", "############## %d", moonphase);
The code is supposed to put the value 0.42 into the moonphase variable, then update the moon_coverage sensor with that value. Also log the value to the console.
However this is the extent of the output:
[09:12:10][D][sensor:121]: 'Moon Coverage': Sending state 0.00000 with 1 decimals of accuracy
[09:12:10][D][main:066]: ############## 0
I’ve hit a brick wall trying to figure this out. if anyone could give me some pointers on getting that json attribute I’d be grateful.