我决定在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));