Search code examples
c++jsonparsingtelegram-bot

cannot use operator[] with a string argument with array (parsing json)


I decided to write a tg bot for weather forecast on c++, and when I need to parse a string in json, always get errors (with numbers works), a lot of googling and found nothing. Please help me, I just will not sleep if I do not understand where messing up.

json library - nlohmann/json (https://github.com/nlohmann/json)

tg api - tgbot-cpp(https://github.com/reo7sp/tgbot-cpp)

Link to json - https://api.openweathermap.org/data/2.5/weather?q=London&appid=2e71c3ca54737820fc305ba048331b8c (api key is free).

parser

std::string get_weather(std::string where) {
    nlohmann::json js_obj = nlohmann::json::parse(get_request("https://api.openweathermap.org/data/2.5/weather?q=London&appid=2e71c3ca54737820fc305ba048331b8c"));
    if(where == "London") {
        return js_obj["weather"]["0"]["main"].get<std::string>();;
    }
}

and when I call this method to parse a string, an error occurs.

bot.getApi().sendMessage(query1->message->chat->id, "Weather: " + get_weather("London")); 
terminate called after throwing an instance of 'nlohmann::json_abi_v3_11_3::detail::type_error'
what():  [json.exception.type_error.305] cannot use operator[] with a string argument with array

but with numbers everything works

float get_temperature(std::string where) {
    auto js_obj = nlohmann::json::parse(get_request("https://api.openweathermap.org/data/2.5/weather?q=London&appid=2e71c3ca54737820fc305ba048331b8c"));
    if(where == "London") {
        return js_obj["main"]["temp"].get<float>();
    }
}
bot.getApi().sendMessage(query1->message->chat->id, "Temperature in your area: "
                        + std::to_string (get_temperature("London") - 273.15));

Solution

  • cannot use operator[] with a string argument with array

    It means that the array subscript value (index value) must be numeric, but you pass a string. The array js_obj["weather"] expects a numeric value 0, not a string "0" when accessing its elements.

    // Wrong
    // js_obj["weather"]["0"]["main"].get<std::string>();
    //                   ^^^
    
    // Fixed
    js_obj["weather"][0]["main"].get<std::string>();
    //                ^