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

json::parse(...) vs json j; j.parse(...) #357

Closed
oneill1979 opened this issue Nov 9, 2016 · 5 comments
Closed

json::parse(...) vs json j; j.parse(...) #357

oneill1979 opened this issue Nov 9, 2016 · 5 comments

Comments

@oneill1979
Copy link

oneill1979 commented Nov 9, 2016

I was wondering if there is a reason that a call to parse on a json object just returns a null json object? The same input seems to parse without issue using the jason::parse call.

For example the following program:

{
    std::string input("{\"happy\":true,\"pi\":3.141}");
    json j;
    j.parse(input);
    std::cout << j.dump() << std::endl;
    j=json::parse(input);
    std::cout << j.dump() << std::endl;
}

Results in (osx):

null
{"happy":true,"pi":3.141}
@nlohmann
Copy link
Owner

nlohmann commented Nov 9, 2016

In the upper example, you create a json object j which is initially null. In line 4, you basically call the static function json::parse(input); which returns the result of the deserialization. As this result is not stored, j remains unchanged. In line 6, you make the same call, but store the result in j, yielding the expected result.

Again: parse is not a member function, but a static function. Calling it as a member function is syntactically OK, but does not change the object you call it from.

@gregmarr
Copy link
Contributor

gregmarr commented Nov 9, 2016

The parse function is static. There is no such thing as calling it "on an object", except that C++ allows you to identify the static function to call using an object instead of the class name.
Your code is equivalent to this:

std::string input("{\"happy\":true,\"pi\":3.141}");
json::parse(input);
std::cout << json().dump() << std::endl;
json j=json::parse(input);
std::cout << j.dump() << std::endl;

@gregmarr
Copy link
Contributor

gregmarr commented Nov 9, 2016

Heh, I saw @nlohmann's answer appear just as I clicked the Comment button. :)

@nlohmann
Copy link
Owner

nlohmann commented Nov 9, 2016

Same here, but Github claims I was 3 seconds faster ;)

@oneill1979
Copy link
Author

Ah, thank you. I had not noticed that it was a static method.

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

3 participants