Iterating through objects in JsonCpp

前端 未结 5 558
北恋
北恋 2020-12-14 07:06

I have a C++ application that uses jsoncpp to decode a JSON string. I have created the following function but it only shows me the top level objects...

How do I get

5条回答
  •  不知归路
    2020-12-14 07:42

    This is a good example that can print either json objects and object member (and it's value) :

    Json::Value root;               // Json root
    Json::Reader parser;            // Json parser
    
    // Json content
    string strCarPrices ="{ \"Car Prices\": [{\"Aventador\":\"$393,695\", \"BMW\":\"$40,250\",\"Porsche\":\"$59,000\",\"Koenigsegg Agera\":\"$2.1 Million\"}]}";
    
    // Parse the json
    bool bIsParsed = parser.parse( strCarPrices, root );
    if (bIsParsed == true)
    {
        // Get the values
        const Json::Value values = root["Car Prices"];
    
        // Print the objects
        for ( int i = 0; i < values.size(); i++ )
        {
            // Print the values
            cout << values[i] << endl;
    
            // Print the member names and values individually of an object
            for(int j = 0; j < values[i].getMemberNames().size(); j++)
            {
                // Member name and value
                cout << values[i].getMemberNames()[j] << ": " << values[i][values[i].getMemberNames()[j]].asString() << endl;
            }
        }
    }
    else
    {
        cout << "Cannot parse the json content!" << endl;
    }
    

    The output :

    {
            "Aventador" : "$393,695",
            "BMW" : "$40,250",
            "Koenigsegg Agera" : "$2.1 Million",
            "Porsche" : "$59,000"
    }
    Aventador: $393,695
    BMW: $40,250
    Koenigsegg Agera: $2.1 Million
    Porsche: $59,000
    

提交回复
热议问题