Karthi
Karthi

Reputation: 51

How to get nested JSON Values using Rapidjson in C++

In the below example, how to take the name and balance?

{
    "user": {
        "Name": "John",
        "Balance": "2000.53"
    }
}

Upvotes: 4

Views: 8398

Answers (3)

InsanitySquared
InsanitySquared

Reputation: 1

This should work too (I just tried it):

rapidjson::Document doc;
doc.Parse(str);
doc["user"]["Balance"].GetString();

Upvotes: 0

cwfighter
cwfighter

Reputation: 502

I don't know Rapidjson much, only know it is a third-party library for parsing json in C++. But I want to say, why don't you use boost for solve this problem. Give you my code, it has solved your problem perfectly.

Before run my code, please install boost library. Strongly recommend it!

#include <boost/property_tree/json_parser.hpp>

#include <string>

#include <sstream>

#include <iostream>

using namespace std;

int main()
{
    boost::property_tree::ptree parser;
    const string str = "{ \"user\": { \"Name\": \"John\", \"Balance\": \"2000.53\" } }";
    stringstream ss(str);
    boost::property_tree::json_parser::read_json(ss, parser);

    //get "user"
    boost::property_tree::ptree user_array = parser.get_child("user");

    //get "Name"
    const string name = user_array.get<string>("Name");
    //get "Balance"
    const string balance = user_array.get<string>("Balance");
    cout << name << ' ' << balance << endl;
    return 0;
}

The codes test well in gcc 4.7, boost 1.57. You can get output: John 2000.53. I think it can solve your problem.

Upvotes: 0

SashaM
SashaM

Reputation: 311

Easy.

rapidjson::Document doc;
doc.Parse(str);
const Value& user = doc["user"];
string name = user["Name"].GetString();
string balance = user["Balance"].GetString();

Upvotes: 15

Related Questions