'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?
Solution 1:[1]
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()
Solution 2:[2]
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';
}
Solution 3:[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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mark Loeser |
Solution 2 | dead beef |
Solution 3 | Gelberth Amarillo Rojas |