代码之家  ›  专栏  ›  技术社区  ›  Anton

不能将运算符[]与数组的字符串参数一起使用(解析json)

  •  0
  • Anton  · 技术社区  · 1 年前

    我决定在c++上编写一个用于天气预报的tg机器人,当我需要用json解析字符串时,总是会出现错误(数字有效),在谷歌上搜索了很多,但一无所获。请帮帮我,如果我不明白哪里搞砸了,我就是睡不着。

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

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

    链接到json- https://api.openweathermap.org/data/2.5/weather?q=London&appid=2e71c3ca54737820fc305ba048331b8c (api密钥是免费的)。

    解析器

    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>();;
        }
    }
    

    当我调用这个方法来解析字符串时,会出现一个错误。

    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
    

    但有了数字,一切都会好起来

    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));
    
    2 回复  |  直到 1 年前
        1
  •  0
  •   3CxEZiVlQ    1 年前

    cannot use operator[] with a string argument with array

    这意味着数组下标值(索引值)必须是数字,但您传递了一个字符串 js_obj["weather"] 访问其元素时需要数值0,而不是字符串“0”。

    // Wrong
    // js_obj["weather"]["0"]["main"].get<std::string>();
    //                   ^^^
    
    // Fixed
    js_obj["weather"][0]["main"].get<std::string>();
    //                ^  
    
        2
  •  0
  •   HeySreelal    1 年前

    我认为,当您在解析器方法中通过传递字符串索引来访问数组项时,会出现上述错误。应该是这样的:

    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>();;
        }
    }