boost::json : Comment vérifier si une valeur existe et a un certain type

Il y a deux méthodes pour vérifier si une valeur existe et a un certain type dans boost::json. Voir ci-dessous pour un exemple complet où vous pouvez tester les deux méthodes. Je recommande généralement l’Option 1 car faire toutes les vérifications 100% correctement est fastidieux et on a tendance à oublier certains cas limites.

Seulement pour les systèmes embarqués où les exceptions sont désactivées (et les activer n’est pas une option), l’Option 2 est la voie à suivre.

Option 1 : Attraper les exceptions

check_value.cpp
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 : Utiliser des vérifications explicites

check_value_explicit.cpp
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;
    }
}

Cas de test complet

check_value_test.cpp
#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;
}

Sortie pour l’Option 1 :

output_option1.txt
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']

Sortie pour l’Option 2 :

Notez que le message d’erreur ici n’est pas très spécifique.

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

Consultez les articles similaires par catégorie : Boost C/C++