Error accessing a nested JSON using boost::json?

71 Views Asked by At

Using the following json:

{
    type: "test",
    version: 1,
    data: {
        name: "omni",
        id: "123",
        value: 3
    }
}

I'm trying to get its data using 2 C++ functions:

void process_data(std::string type, std::string data)
{
        boost::json::value data = boost::json::parse(data);
        std::string name = json.at("name").as_string().c_str();
        std::string id = json.at("id").as_string().c_str();
        int value = json.at("value").as_int64();

        std::cout << "Message data content:" << std::endl;
        std::cout << "Name: " << name << std::endl;
        std::cout << "Id: " << id << std::endl;
        std::cout << "Value: " << value << std::endl;
}

void process_message(std::string payload)
{
        boost::json::value json = boost::json::parse(payload);
        std::string type = json.at("type").as_string().c_str();
        int version = json.at("version").as_int64();

        std::cout << "Message received:" << std::endl;
        std::cout << "Type: " << type << std::endl;
        std::cout << "Version: " << version << std::endl;

        std::string data = json.at("data").as_string().c_str(); !!! Getting error here
        process_data(data);
}

I'm getting the following error when parsing data:

terminate called after throwing an instance of 'boost::wrapexcept<std::invalid_argument>'
  what():  not a string
Aborted (core dumped)

Any ideas on how to fix it?

1

There are 1 best solutions below

2
On

You can not treat a JSON object as if it is a string. As the commenter says, serialize it instead:

std::string data = serialize(json.at("data"));

However serializing is an anti-pattern unless you are going to send over (text) protocol. Instead, pass the json value:

process_data(json.at(“data”));

The best part is that it will include the type if it’s variant.