Parse JSON array as std::string with Boost ptree

前端 未结 3 1582
花落未央
花落未央 2020-12-10 18:03

I have this code that I need to parse/or get the JSON array as std::string to be used in the app.

std::string ss = \"{ \\\"id\\\" : \\\"123\\\", \\\"number\         


        
3条回答
  •  粉色の甜心
    2020-12-10 18:26

    Arrays are represented as child nodes with many "" keys:

    docs

    • JSON arrays are mapped to nodes. Each element is a child node with an empty name. If a node has both named and unnamed child nodes, it cannot be mapped to a JSON representation.

    Live On Coliru

    #include 
    #include 
    
    using boost::property_tree::ptree;
    
    int main() {
        std::string ss = "{ \"id\" : \"123\", \"number\" : \"456\", \"stuff\" : [{ \"name\" : \"test\" }, { \"name\" : \"some\" }, { \"name\" : \"stuffs\" }] }";
    
        ptree pt;
        std::istringstream is(ss);
        read_json(is, pt);
    
        std::cout << "id:     " << pt.get("id") << "\n";
        std::cout << "number: " << pt.get("number") << "\n";
        for (auto& e : pt.get_child("stuff")) {
            std::cout << "stuff name: " << e.second.get("name") << "\n";
        }
    }
    

    Prints

    id:     123
    number: 456
    stuff name: test
    stuff name: some
    stuff name: stuffs
    

提交回复
热议问题