Parse JSON array response

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… :frowning:

Please note, that the result is an array, not a single object.

Kind regards,
m@rko

x[0]["USEROK"]

Show the code you’ve been trying if this doesn’t help — you’ve not given much context.

I accept the critic, I was too quick :slight_smile:

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") {
      |                 ^

root[0][“USEROK”] doesn’t work :frowning:

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?

Exactly, the string is displayed in the log

Can you paste it here please? Or is it exactly the same as in your first post?

[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

Try root[0].["USEROK"] - note the .

Useful site https://jsonpathfinder.com/

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.

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)

Which one?

this one is correct - abut the tool - I foud the link you provided (first time I missed it)

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…