Json::Value.get() and [] operator

2009-05-29
2014-04-19
  • Chris Bartley
    Chris Bartley
    2009-05-29

    According to the example at http://jsoncpp.sourceforge.net/ if you try to access a property which doesn't exist by using the [] operator, it will return a null value.  E.g.:

    // Get the value of the member of root named 'encoding', return a 'null' value if
    // there is no such member.
    const Json::Value plugins = root["plug-ins"];

    That's true if "root" is of Json::objectValue type, but will fail with an assertion if it's an array type (and presumably any type other than objectValue.  Same goes for the get() method and the isMember() method, e.g. root.get("plug-ins") or root.isMember("plug-ins").

    It would be nice if the code did some error checking instead of just immediately failing with the assertion.  That is, have the implementation do the check for whether it's of Json::objectValue type.  If it is and the property exists, then return it.  Otherwise, just return Json::Value::null.  It's a drag having to do this check myself all the time.

    Thanks.

     
  • Dmitry D
    Dmitry D
    2014-02-14

    It has been 5 years since the previous post, but the problem is still there.

    I have just spent a few hours trying to figure out why our application crashes only to find out that in some rare cases the input string that was supposed to contain JSON object actually contained an integer.

    The string was passed to the jsoncpp parser and then isMember() was called to check existence of a particular value, which caused the application to crash (in Release mode).

    It would be really nice if JSON_ASSERT in operator[] implementation was replaced with JSON_ASSERT_MESSAGE that throws an exception instead of calling assert().
    (JSON_ASSERT_MESSAGE is already defined in the same source file)

    jsoncpp version: 0.6.9-rc2, amalgamated

     
  • Done.

    Same as fix for bug 67.