C++ Telegram天气机器人用nlohmann/json解析JSON字符串遇类型错误求助
错误原因及修正方案
核心问题
你遇到的错误是因为OpenWeatherMap返回的weather字段是JSON数组,而非对象,但你用了字符串类型的索引"0"去访问数组元素,nlohmann/json库不允许对数组使用字符串参数的operator[],所以抛出类型错误。
具体分析
OpenWeatherMap的weather字段结构大概是这样的(简化版):
{ "weather": [ { "main": "Clouds", "description": "scattered clouds" } ] }
可以看到weather是一个数组,数组元素需要用整数索引(比如0)访问,而不是字符串"0"。你的温度函数能正常运行,是因为main是JSON对象,用字符串键"temp"访问是合法的。
修正后的代码
把get_weather函数里的js_obj["weather"]["0"]["main"]改成js_obj["weather"][0]["main"]即可:
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>(); } // 补充默认返回值,避免函数无返回路径触发未定义行为 return ""; }
额外建议
- 可以先判断
weather数组是否为空,避免访问越界:if (!js_obj["weather"].empty()) { return js_obj["weather"][0]["main"].get<std::string>(); } else { return "No weather data available"; } - 确保函数所有分支都有返回值,这是C++的基本规范,否则会导致未定义行为。
内容的提问来源于stack exchange,提问作者Anton
相关产品推荐
相关产品推荐

