4

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

{
    "user": {
        "Name": "John",
        "Balance": "2000.53"
    }
}
mtb
  • 1,350
  • 16
  • 32
Karthi
  • 51
  • 1
  • 3

2 Answers2

15

Easy.

rapidjson::Document doc;
doc.Parse(str);
const Value& user = doc["user"];
string name = user["Name"].GetString();
string balance = user["Balance"].GetString();
SashaM
  • 311
  • 1
  • 7
  • When I try to apply this solution I get this error message. "error: 'Value' does not name a type" – Raj Sep 19 '22 at 13:57
  • Okay, for those who get this error solution is const rapidjson::Value& user = doc["user"]; – Raj Sep 19 '22 at 14:02
0

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.

mtb
  • 1,350
  • 16
  • 32
cwfighter
  • 502
  • 1
  • 5
  • 20