Iterating through objects in JsonCpp

前端 未结 5 551
北恋
北恋 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:37

    If you are just looking to print out the Json::Value, there's a method for that:

    Json::Value val;
    /*...build the value...*/
    cout << val.toStyledString() << endl;
    

    Also, you may want to look into the Json::StyledWriter, the documentation for it is here. I believe it print a human friendly version. Also, Json::FastWriter, documentation here, prints a more compact form.

    0 讨论(0)
  • 2020-12-14 07:42

    You have some errors related to seemingly not having a great handle on recursion or the key->value nature of JSON and how that relates to the library you're using. I haven't tested this code at all, but it should work better.

    void CDriverConfigurator::PrintJSONValue( const Json::Value &val )
    {
        if( val.isString() ) {
            printf( "string(%s)", val.asString().c_str() ); 
        } else if( val.isBool() ) {
            printf( "bool(%d)", val.asBool() ); 
        } else if( val.isInt() ) {
            printf( "int(%d)", val.asInt() ); 
        } else if( val.isUInt() ) {
            printf( "uint(%u)", val.asUInt() ); 
        } else if( val.isDouble() ) {
            printf( "double(%f)", val.asDouble() ); 
        }
        else 
        {
            printf( "unknown type=[%d]", val.type() ); 
        }
    }
    
    bool CDriverConfigurator::PrintJSONTree( const Json::Value &root, unsigned short depth /* = 0 */) 
    {
        depth += 1;
        printf( " {type=[%d], size=%d}", root.type(), root.size() ); 
    
        if( root.size() > 0 ) {
            printf("\n");
            for( Json::Value::const_iterator itr = root.begin() ; itr != root.end() ; itr++ ) {
                // Print depth. 
                for( int tab = 0 ; tab < depth; tab++) {
                   printf("-"); 
                }
                printf(" subvalue(");
                PrintJSONValue(itr.key());
                printf(") -");
                PrintJSONTree( *itr, depth); 
            }
            return true;
        } else {
            printf(" ");
            PrintJSONValue(root);
            printf( "\n" ); 
        }
        return true;
    }
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-14 07:46

    Given member names, get the values

    // Print all items under data1 value
    vector<string> memberNames = root["test1"]["data1"].getMemberNames();
    for (const string& mn : memberNames)
    {
        cout << "[" << mn << "]:" << "[" << root["test1"]["data1"].get(mn, "None") << "]" << endl;
    }
    
    0 讨论(0)
  • 2020-12-14 07:50

    There is an easy way to iterate over all fields in json::value. I omitted the printf stuff.

    #include "cpprest/json.h"
    #include "cpprest/filestream.h"
    
    using web::json::value;
    using std::wstring;
    
    static void printOneValue(const wstring &key, const double &value);
    static void printOneValue(const wstring &key, const bool &value);
    static void printOneValue(const wstring &key, const int &value);
    static void printOneValue(const wstring &key, const wstring &value);
    static void printOne(const wstring &key, const value &v, _num level);
    static void printTree(const value &v);
    
    static void printTree(const value &v)
    {
        if(!v.is_object())
            return;
    
        try
        {
            printOne(wstring(), v, 0);
        }
        catch(...)
        {
            // error handling
        }
    }
    
    static void printOne(const wstring &key, const value &v, _num level)
    {
        switch(v.type())
        {
        case value::value_type::Number:
            if(v.is_double())
                printOneValue(key, v.as_double());
            else
                printOneValue(key, v.as_integer());
            break;
        case value::value_type::Boolean:
            printOneValue(key, v.as_bool());
            break;
        case value::value_type::String:
            printOneValue(key, v.as_string());
            break;
        case value::value_type::Object:
            for(auto iter : v.as_object())
            {
                const wstring &k = iter.first;
                const value &val = iter.second;
                printOne(k, val, level+1);
            }
            break;
        case value::value_type::Array:
            for(auto it : v.as_array())
            {
                printOne(key, it, level+1);
            }
            break;
        case value::value_type::Null:
        default:
            break;
        }
    }
    
    static void printOneValue(const wstring &key, const wstring &value)
    {
        // process your key and value
    }
    
    static void printOneValue(const wstring &key, const int &value)
    {
        // process your key and value
    }
    
    static void printOneValue(const wstring &key, const double &value)
    {
        // process your key and value
    }
    
    static void printOneValue(const wstring &key, const bool &value)
    {
        // process your key and value
    }
    
    0 讨论(0)
提交回复
热议问题