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

7.9k views Asked by At

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

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

There are 2 answers

0
cwfighter On

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.

2
SashaM On

Easy.

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