boost::json : How to check if value exists and has a certain type

There are two methods to check if a value exists and has a certain type in boost::json. See below for a full example where you can test both methods. I generally recommend Option 1 as doing all the checks 100% correctly is cumbersome and one often tends to forget some edge cases.

Only for embedded systems where exceptions are disabled (and enabling them is not an option), Option 2 is the way to go.

Option 1: Catch exceptions

void extractTimestamp(const boost::json::value& jv) {
    try {
        double timestamp = jv.as_object().at("timestamp").as_double();
        std::cout << "Timestamp: " << timestamp << std::endl;
    } catch (const boost::system::system_error& e) {
        std::cerr << "Error" << e.code() << ": " << e.what() << std::endl;
    }
}

Option 2: Use explicit checks

void extractTimestamp2(const boost::json::value& jv) {
    // Extract the timestamp as a double
    if (jv.is_object() && jv.as_object().contains("timestamp")) {
        double timestamp = jv.as_object().at("timestamp").as_double();
        std::cout << "Timestamp: " << timestamp << std::endl;
    } else {
        std::cerr << "Error: 'timestamp' field is missing in the JSON data." << std::endl;
    }
}

Full test case

#include <boost/json.hpp>
#include <iostream>

// TODO: Insert one of the extractTimestamp functions here!

int main() {
    // Test with correct JSON
    {
        std::string line = "{\"timestamp\":1675910171.91}";
        boost::json::value jv = boost::json::parse(line);
        extractTimestamp(jv);
    }

    // Test with incorrect JSON #1
    {
        std::string line = "{}";
        boost::json::value jv = boost::json::parse(line);
        extractTimestamp(jv);
    }
    
    // Test with incorrect JSON #2
    {
        std::string line = "[]";
        boost::json::value jv = boost::json::parse(line);
        extractTimestamp(jv);
    }

    return 0;
}

Output for Option 1:

Timestamp: 1.67591e+09
Error boost.json:17: out of range [boost.json:17 at /usr/include/boost/json/impl/object.hpp:388 in function 'at']
Error boost.json:31: value is not an object [boost.json:31 at /usr/include/boost/json/value.hpp:2529 in function 'as_object']

Output for Option 2:

Note that the error message here is not very specific.

Timestamp: 1.67591e+09
Error: 'timestamp' field is missing in the JSON data.
Error: 'timestamp' field is missing in the JSON data.