mardi 29 octobre 2019

property_tree get array value as String

I want to parse a json file/string with boosts property_tree, but instead of having sub-trees parsed into an array I would like it to stay as a string for use in another existing function which only deals with json-Strings.

I hope the following example is sufficient:


example.json

{
    "type": "myType",
    "colors": {
        "color0":"red",
        "color1":"green",
        "color2":"blue"
    }
}

main.cpp

std::stringstream ss("example.json");
ptree pt;
read_json(ss, pt);

std::string sType = pt.get("type", "");
std::string sColors = pt.get<std::string>("colors");

std::cout << "sType: " << sType << std::endl; // sType: myType
std::cout << "sColors: " << sColors << std::endl; // sColors: {"color0":"red", "color1":"green", "color2":"blue"}

I've tried several functions, for example pt.get_child("colors") would just return another ptree and pt.get_value<std::string>("colors") does return an empty string ("").

The desired output would look like this:

sColors: {"color0":"red", "color1":"green", "color2":"blue"}

or

sColors: {\"color0\":\"red\", \"color1\":\"green\", \"color2\":\"blue\"}

Is there a way to recive the desired output for sColors?

Aucun commentaire:

Enregistrer un commentaire