0

Trying to figure out a general to-go way for JSON value parsing.

  • No error checking:

    myField = jsonValue["myField"].as_string();`
    
  • With error checking:

    if (jsonValue.is_null())
        return false;
    
    if (!jsonValue.is_object())
        return false;
    
    for (auto it = jsonValue.as_object().cbegin(); it != jsonValue.as_object().cend(); ++it)
    {
        const std::string& str = it->first;
        const json::value& v = it->second;
    
        if (str == "myField")
        {
            if (v.is_string())
            {
                myField = v.as_string();
                continue;
            }
            else
            {
                return false;
            }
        }
    }
    

The difference in amount of code is noticeable. Should I bother with error checking or the first approach would be enough?

CorellianAle
  • 645
  • 8
  • 16
  • Maybe validate your json with a json-schema before processing it ? – Jarod42 Dec 11 '17 at 15:29
  • What do you mean exactly? Working with JSON for the first time. Quick search just points me to several online validators. – CorellianAle Dec 11 '17 at 17:31
  • json schema is a way to describe expected json: (should have field "myField" of type string, ...). So you can handle error from schema first. If no errors from schema, you can avoid some error checking. – Jarod42 Dec 11 '17 at 18:00

1 Answers1

0

This question would probably be best suited at https://codereview.stackexchange.com/ but if you have a requirement to handle errors gracefully, you should prefer code that has robust error handling.

Justin Randall
  • 2,243
  • 2
  • 16
  • 23