ZippoSLO
(Marko)
February 23, 2023, 1:18pm
1
Hello!
Question - How do I parse the JSON result that comes as an array
[
{
"USEROK":1
}
]
I tried a lot of things in ESPHome, but I just can’t get the value of USEROK…
Please note, that the result is an array, not a single object.
Kind regards,
m@rko
Troon
(Troon)
February 23, 2023, 1:19pm
2
x[0]["USEROK"]
Show the code you’ve been trying if this doesn’t help — you’ve not given much context.
ZippoSLO
(Marko)
February 23, 2023, 1:31pm
3
Troon:
x[0]["USEROK"]
I accept the critic, I was too quick
the code that I have:
- lambda: |-
json::parse_json(id(http_request_data).get_string(), [](JsonObject root) {
if (root["USEROK"] == "1") {
id(lock).turn_on();
ESP_LOGD("lock", "Access granted");
}
else {
ESP_LOGD("lock", "Access denied");
}
});
if I change to root[0][“USEROK”], I get an error:
/config/esphome/kljucavnica.yaml:111:17: error: no match for 'operator[]' (operand types are 'ArduinoJson::JsonObject' {aka 'ArduinoJson6185_D1::ObjectRef'} and 'int')
111 | if (root[0]["USEROK"] == "1") {
| ^
ZippoSLO
(Marko)
February 24, 2023, 6:58am
4
root[0][“USEROK”] doesn’t work
Troon
(Troon)
February 24, 2023, 7:28am
5
I don’t have much experience of JSON within ESPHome, sorry. How do you know what the structure looks like? What do you get if you write root
straight to the logs?
ZippoSLO
(Marko)
February 24, 2023, 9:21am
6
Exactly, the string is displayed in the log
Troon
(Troon)
February 24, 2023, 9:28am
7
Can you paste it here please? Or is it exactly the same as in your first post?
ZippoSLO
(Marko)
February 24, 2023, 9:57am
8
[10:57:14][D][wiegand:073]: received 26-bit tag: 3052795
[10:57:14][I][TAG:095]: received tag 3052795
[10:57:14][D][main:106]: Got REST response: [{"USEROK":0}]
[10:57:14][D][lock:119]: Access denied
[10:57:14][D][http_request:099]: HTTP Request completed; URL: http://192.168.66.17:3000/api/cards/?card=3052795&location=4; Code: 200; Duration: 25 ms
nickrout
(Nick Rout)
February 24, 2023, 10:06am
9
ZippoSLO:
root[0][“USEROK”],
Try root[0].["USEROK"]
- note the .
Useful site https://jsonpathfinder.com/
Troon
(Troon)
February 24, 2023, 10:10am
10
nickrout:
Try root[0].["USEROK"]
That’s not valid JSON spec. root[0].USEROK
, root.0.USEROK
, or root[0]["USEROK"]
are fine but you can’t mix dots and brackets like that.
ZippoSLO
(Marko)
February 24, 2023, 10:21am
11
It works, thank you!
Just for curiosity, how do you test if the syntax is correct? Is there any tool for this? To input the JSON and to write the “path” (for example " root[0].["USEROK"]
") and see the result (or error if wrong)
ZippoSLO
(Marko)
February 24, 2023, 10:25am
13
nickrout:
Try root[0].["USEROK"]
this one is correct - abut the tool - I foud the link you provided (first time I missed it)
Troon
(Troon)
February 24, 2023, 10:26am
14
ZippoSLO:
Try root[0].["USEROK"]
Then you should put the solution mark against @nickrout ’s suggestion, although I don’t see how that is correct — it doesn’t conform to any JSON spec I’ve ever seen…