Skip to content
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

Unexpected behaviour of is_null #1112

Closed
phyz777 opened this issue May 28, 2018 · 4 comments
Closed

Unexpected behaviour of is_null #1112

phyz777 opened this issue May 28, 2018 · 4 comments

Comments

@phyz777
Copy link

phyz777 commented May 28, 2018

The following code produces unexpected output (which is, all four statements being printed):

#include <iostream>

#include "json.hpp"

int main()
{
    nlohmann::json j;

    if (j.empty()) {
        std::cout << "Object is empty" << std::endl;
    }

    if (j.is_null()) {
        std::cout << "Object is null" << std::endl;
    }

    nlohmann::json k;

    j["aminull"] = k;

    if (j["aminull"].empty()) {
        std::cout << "Object under key is empty" << std::endl;
    }

    if (j["aminull"].is_null()) {
        std::cout << "Object under key is null" << std::endl;
    }

    return 0;
}

I am not entirely sure whether or not this is the expected behaviour, but I think it would be more intuitive to have only the empty() conditions evaluate to true and the others to false?

Best wishes and thanks for the great work!

@phyz777
Copy link
Author

phyz777 commented May 28, 2018

By the way, the following works as expected:

    nlohmann::json l = nlohmann::json::object();

    if (l.empty()) {
        std::cout << "Object is also empty" << std::endl;
    }

    if (l.is_null()) {
        std::cout << "Object is also null" << std::endl;
    }

If all of this is intended to work like this: sorry for the hassle and please, feel free to silently delete this issue.

@nlohmann
Copy link
Owner

Please note:

  • Uninitialized JSON values are null by default.
  • empty() returns true if and only if size() == 0.
  • null values have the size 0, because they have no value (see documentation).
  • objects/arrays are empty if they have no entries.

In your second example, I do not believe that l.is_null() is true.

@phyz777
Copy link
Author

phyz777 commented May 28, 2018

Yes, indeed, is_null does not evaluate to true here, this is what I meant with 'works as expected'.
Well, in this case, everything is just fine. Feel free to delete or close this issue. (:

@nlohmann
Copy link
Owner

No worries - every ticket may be helpful for others and give me an idea what needs to be documented more thoroughly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants