rocx
rocx

Reputation: 285

Convert json value to int in c++

I'm reading a json value in c++ using

Json::Reader reader

and the value is stored in Json::Value root

This root contains "age" and "id" and I want to convert root["age"] to int.

I tried to convert it to string using .str() but could not get.

Any suggestion?

Upvotes: 10

Views: 19961

Answers (3)

If you cannot convert directly to int, first convert to string, then to int

                    string age = root["age"].asString();
                    int age2 = std::stoi(age);

Upvotes: 0

Mark Loeser
Mark Loeser

Reputation: 18637

In jsoncpp they provide helper methods on the Json::Value object. You can merely call the asInt() method on the value to convert it.

int ageAsInt = root["age"].asInt()

Upvotes: 13

dead beef
dead beef

Reputation: 683

You should be able to use

std::stoi( string )

Example taken from http://en.cppreference.com/w/cpp/string/basic_string/stol

#include <iostream>
#include <string>

int main()
{
    std::string test = "45";
    int myint = std::stoi(test);
    std::cout << myint << '\n';
}

Upvotes: 1

Related Questions