使用nlohmann json库解析文件时accept返回true却遇解析错误
问题原因
你遇到的问题核心是文件流的读指针位置问题:
当调用nlohmann::json::accept(ifs)时,函数会读取整个文件流的内容来校验JSON格式,完成后文件流的读指针会停在文件末尾。此时再调用json::parse(ifs),流中已经没有可读取的数据,因此触发解析错误。
解决方案
提供三种可行的解决方式,按需选择:
方式1:重置文件流指针
在调用accept后,手动重置流的状态和读指针到文件开头:
using json = nlohmann::json; int main() { ifstream ifs("test.json"); if (nlohmann::json::accept(ifs)) { cout << "accepted" << endl; // 重置流状态和指针 ifs.clear(); ifs.seekg(0); } else { cout << "not accepted" << endl; return 1; } json j = json::parse(ifs); }
方式2:跳过单独的accept校验
json::parse本身会自动校验JSON格式,失败时会抛出异常,无需提前调用accept。如果不需要先打印"accepted"提示,可以简化代码:
using json = nlohmann::json; int main() { ifstream ifs("test.json"); try { json j = json::parse(ifs); // 解析成功后的逻辑 } catch (const json::parse_error& e) { cout << "解析错误: " << e.what() << endl; } }
方式3:先读取文件到字符串再解析
把文件内容一次性读到字符串中,既可以用accept验证,也能重复使用内容解析:
using json = nlohmann::json; #include <sstream> int main() { ifstream ifs("test.json"); stringstream buffer; buffer << ifs.rdbuf(); string json_str = buffer.str(); if (nlohmann::json::accept(json_str)) { cout << "accepted" << endl; json j = json::parse(json_str); } else { cout << "not accepted" << endl; } }
内容的提问来源于stack exchange,提问作者dailypassby
相关产品推荐
相关产品推荐

