Hi
I’m trying to parse JSON in esphome using json::parse_json, but I think I’m hitting upon some weird wide character/utf8 type issues.
Following the example here HTTP Request — ESPHome under “GET values from a JSON body response” I have a sample configuration below: -
substitutions:
device_name: screen-2
friendly_name: Screen 2
esphome:
name: $device_name
friendly_name: $friendly_name
esp32:
board: esp32dev
framework:
type: arduino
logger:
api:
encryption:
key: "obfuscated"
ota:
password: "obfuscated"
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
# Enable fallback hotspot (captive portal) in case wifi connection fails
ap:
ssid: "Screen-2 Fallback Hotspot"
password: "obfuscated"
captive_portal:
json:
http_request:
id: http_request_data
useragent: esphome/device
timeout: 10s
button:
- platform: template
name: Test Button
on_press:
then:
- http_request.get:
url: http://ip.jsontest.com/
on_response:
then:
- lambda: |-
json::parse_json(id(http_request_data).get_string(), [](JsonObject root) {
ESP_LOGD("one", "The value is: %s", root["ip"]);
ESP_LOGD("two", root["ip"]);
});
When I press the button, this calls a website which returns IP address in JSON. However, when I try and do something with the parsed output, I get issues if I try and use it as a string. See the first line in the output below: -
[23:30:46][D][one:052]: The value is: \x80\x80p"\xfb?X"\xfb?Y\xb3@?`
[23:30:46][D][two:053]: 69.69.69.69
[23:30:46][D][http_request:099]: HTTP Request completed; URL: http://ip.jsontest.com/; Code: 200; Duration: 302 ms
That’s with logging using %s, so clearly it isn’t just a char* - I think it’s probably utf8 or similar wide encoding. And if I pass it directly as per the “two” logger above, it comes out correct (albeit I’ve obfuscated the address).
So how do I make the output be a usable, displayable string? My actual use case is to display on a screen, and often I use .c_str() but it’s not a std::string object so that doesn’t work. I’ve tried casting with (char), doing sprintf() with “%ls” and can’t get a human readable output.
Any ideas?
Thanks