pfc
pfc

Reputation: 1910

Error: call of overloaded 'stoi(nlohmann::basic_json<>::value_type&)' is ambiguous

I'm using the Json for modern C++ project here. I met with the following problem. The obj_json is a json object and I want to get the value of obj_json["key"][0][1], which shall be an integer value. Therefore I wrote:

int id;
id = obj_json["key"][0][1];

I met with the error saying:

terminate called after throwing an instance of 'std::domain_error'
  what():  type must be number, but is string

So I change the code to:

int id;
id = std::stoi(obj_json["key"][0][1]);

I get the following error:

error: call of overloaded 'stoi(nlohmann::basic_json<>::value_type&)' is ambiguous
In file included from /home/mypath/gcc-5.4.0/include/c++/5.4.0/string:52:0,
             from /home/mypath/gcc-5.4.0/include/c++/5.4.0/stdexcept:39,
             from /home/mypath/gcc-5.4.0/include/c++/5.4.0/array:38,
             from ../json-develop/src/json.hpp:33,
             from libnba.cpp:1:
/home/mypath/gcc-5.4.0/include/c++/5.4.0/bits/basic_string.h:5258:3: note: candidate: int std::__cxx11::stoi(const string&, std::size_t*, int)
   stoi(const string& __str, size_t* __idx = 0, int __base = 10)
   ^
/home/mypath/gcc-5.4.0/include/c++/5.4.0/bits/basic_string.h:5361:3: note: candidate: int std::__cxx11::stoi(const wstring&, std::size_t*, int)
   stoi(const wstring& __str, size_t* __idx = 0, int __base = 10)

I'm confused with this. As shown in the first error message, the obj_json["key"][0][1] is a string. But in the second error message, why does the error happens? I also print out the type of the object, using the following code:

cout << typeid(obj_json["key"][0][1]).name() << endl;

The type printed is

N8nlohmann10basic_jsonISt3mapSt6vectorNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEblmdSaEE

I'm totally confused... How to solve this? Thank you for helping me!

Upvotes: 0

Views: 2422

Answers (2)

pfc
pfc

Reputation: 1910

I find an answer that seems helpful here. In the answers of this issue, someone said basic_json can convert to both a char and a std::string, which made the compiler did not know the type of an object. I don't know whether this is the reason for my own problem. But the following solution works for me:

int id;
str temp_str_val;
temp_str_val = obj_json["key"][0][1];
id = stoi(temp_str_val);

That is, declare a string variable and copy the value to it first. Then call stoi on the string variable. This only makes my code work, but does not answer my question that why this happens. I'm still looking forward to better solutions. Thank you all for helping me!

Upvotes: 3

user31264
user31264

Reputation: 6727

Your problem is obj_json["key"][0][1] is not a string. Its type is: nlohmann::basic_json<>::value_type . You should look for the library, and check what is the nlohmann::basic_json<>::value_type, and how to convert it to number.

Upvotes: 3

Related Questions