-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
JsonVariant tests false for both a value that doesn't exist and for a value that is zero #2083
Comments
Hi @judge2005, Thank you for this feedback but I don't see any problem since this behavior is consistent with the conversion to JsonVariant var;
var.as<bool>(); // false
JsonDocument doc;
var = doc.to<JsonVariant>();
var.as<bool>(); // false
var.set(false);
var.as<bool>(); // false
var.set(true);
var.as<bool>(); // true
var.set(0);
var.as<bool>(); // false
var.set(1);
var.as<bool>(); // true
var.set(nullptr);
var.as<bool>(); // false
var.set("hello world");
var.as<bool>(); // true
var = doc.to<JsonArray>();
var.as<bool>(); // true
var = doc.to<JsonObject>();
var.as<bool>(); // true Best regards, |
The problem is that using operator[] I can’t tell the difference between an attribute that doesn’t exist and one that does exist but who’s value is zero. However that is the solution recommended by the documentation. In reality I have to use containsKey(). |
You can use |
That is good, but I am trying to make the point that the documentation is misleading. If it is followed it would lead to code that does not function correctly. The documentation states that operator[] can be used to determine if an attribute is present or not because it returns false if the attribute is not present. In fact it will also return false if the attribute is present but is either a numeric zero or a boolean false. |
Which part of the documentation are you referring to? |
https://arduinojson.org/v7/api/jsonvariant/containskey/ The text under the heading "Avoid this function when you can!" Because ArduinoJson implements the Null Object Pattern, it is always safe to read the object: if the key doesn’t exist, it returns an empty value. Which is only true in the sense that it will always return something rather than throwing an exception. |
I'm sorry I don't see any problem with this paragraph. |
Describe the bug
In v7 JsonVariant tests false for both a value that doesn't exist and for a value that is zero, yet the documentation recommends that operator[] be used to test if a key is there rather than containsKey().
Troubleshooter report
I don't see how the troubleshooter can be used to answer this
Environment
Here is the environment that I used:
Reproduction
Here is a small snippet that reproduces the issue.
Program output
If relevant, include the repro program output.
Expected output:
Actual output:
The text was updated successfully, but these errors were encountered: