Skip to content

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

Closed

Description

@oneill1979

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}

Activity

  1. nlohmann commented on Nov 9, 2016

    @nlohmann
    Owner

    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.

  2. gregmarr commented on Nov 9, 2016

    @gregmarr
    Contributor

    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;
    
  3. gregmarr commented on Nov 9, 2016

    @gregmarr
    Contributor

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

  4. nlohmann commented on Nov 9, 2016

    @nlohmann
    Owner

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

  5. oneill1979 commented on Nov 9, 2016

    @oneill1979
    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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions