c++jsoncasablanca

Difference between web::json::value::parse and web::json::value::string in Casablanca C++ REST SDK


I have a piece of code that looks like this (obj is a web::json::value):

try {
    obj[key_str] = web::json::value::parse(value_str);
}
catch (...) {
    obj[key_str] = web::json::value::string(value_str);
}

I am not able to find the difference between the two because for any input value_str that I give, such as the string "value1", only the statement inside the catch runs.

So my question is - what is the exact difference between ::string() and ::parse()?

Could you show me a minimal example that demonstrates this difference? I am not able to differentiate between these two functions from the documentation alone.


Solution

  • parse takes a string and forms a json object out of it:

    {"id": 1,"title": "test" }
    

    Will give you an object of size 2, containing id = 1, and title = "test".

    string takes a string and forms a json string out of it.

    The later example will return à json string containing "id": 1,"title": "test".

    This basically means that you are trying to parse a json string which is not recognized as a json object. That will be the case with the example your are giving.

    parse(const std::string& s)  { 
       std::cout << json.parse(s) << std::endl;
       std::cout << json.parse(s).size() << std::endl;
       std::cout << json.parse(s).type() << std::endl;
       std::cout << json.string(s) << std::endl;
       std::cout << json.string(s).size() << std::endl;
       std::cout << json.string(s).type() << std::endl;             
    }
    

    For {"id": 1,"title": "test" } return :

    {"body":"body test","id":1,"title":"test","userId":1}
    4
    3
    "{\"userId\":1, \"id\": 1,\"title\": \"test\",\"body\": \"body test\"}"
    0
    2
    

    Notice the size of the json object and the fact the json string is between quotation and of size 0 instead of 4. Take a look at the type 3 (object) and 2 string.

    For "value 1", which is not a json, it is a string, you will have:

    "value 1"
    0
    "\"value 1\""
    0
    

    Notice here the 2 objects are of size 0, and type 2 (string).
    This is the value of the type:

    enum value_type
            {
                /// Number value
                Number,
                /// Boolean value
                Boolean,
                /// String value
                String,
                /// Object value
                Object,
                /// Array value
                Array,
                /// Null value
                Null
            };