lolpop16
lolpop16

Reputation: 57

C++ JsonCpp: Loop through objects and get value

I got a little problem. My json looks like this:

{
"data" : 
{
    "Money" : 
    {
        "testUser3" : "500",
        "testUser2" : "23",
        "testUser1" : "2435",
        "testUser" : "60"
    }
}}

And I am trying to get the value + names of all the users.. but I don't know how, because the user names can change I can't use root["data"]["Money"]["testUser"].asInt(); I hope someone can help me, thanks.

Upvotes: 0

Views: 5262

Answers (1)

Goodies
Goodies

Reputation: 2069

you were downvoted, but I'll help you anyway, cause I need something similar.. let's thank Brandon in JsonCpp - when having a json::Value object, how can i know it's key name? for the keys part..

#include <string>
#include <iostream>

#include "jsoncpp-master/include/json/value.h"
#include "jsoncpp-master/include/json/json.h"

using namespace std;

bool Testjson2()
{
    string s =
        "   { \"data\" :{"
        "           \"Money\" : {"
        "               \"testUser3\" : \"500\","
        "               \"testUser2\" : \"23\","
        "               \"testUser1\" : \"2435\","
        "               \"testUser\"  : \"60\""
        "           }"
        "   } }";
    Json::Value root;
    Json::Reader reader;
    string sdress = "{\"\":[" + s + "]}";
    if (!reader.parse(sdress, root))
    {
        cout << sdress << "\n" << "Parse error\n";
        return false;
    }
    const Json::Value datasections = root[""];
    Json::Value  v = datasections [0]["data"]["Money"];
    cout << "There are " << v.size() << " members\n";
    for (auto const& id : v.getMemberNames()) 
        cout << id << " has " << v[id] << std::endl;
    return true;
}

Upvotes: 2

Related Questions