boost::json how to extract double attribute from JSON object minimal example

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

int main() {
    // The JSON string to parse
    std::string json_str = "{\"timestamp\":1675910171.91}";

    // Parse the JSON string
    boost::json::value jv = boost::json::parse(json_str);

    // Extract the timestamp as a double
    double timestamp = jv.as_object()["timestamp"].as_double();

    // Output the result
    std::cout << "Timestamp: " << timestamp << std::endl;

    return 0;
}

Compile like this:

example.sh
g++ -o jsontest jsontest.cpp -lboost_json

Example output

example.txt
Timestamp: 1.67591e+09

Check out similar posts by category: Boost, C/C++