Nlohmann JSON从文件中阅读

nlohmann json reading from file

本文关键字:文件 JSON Nlohmann      更新时间:2023-10-16

我目前以这种方式在文件中阅读:

using json = nlohmann::json;
std::ifstream jsonConfigFileStream("/path/to/file.json", std::ifstream::in);
json jsonConfigRoot;
if (jsonConfigFileStream.is_open()) {
  jsonConfigFileStream >> jsonConfigRoot;
}

但是,它一直给我带来错误

libc++abi.dylib: terminating with uncaught exception of type std::invalid_argument
Abort trap: 6

错误应来自代码jsonConfigFileStream >> jsonConfigRoot

有人可以启发我发生的事情吗?

JSON文件中可能存在错误。在某些衬里中检查正确性。nlohmann json parser也不喜欢悬挂的分离器,例如

{"node":[1,2,3,4,]}
                ^

其他失败案例 - 除了数字以外的任何其他内容。

将其包裹在try...catch和对数运行时错误中 - 在大多数情况下,它确实解释了为什么解析失败

如果此条件良好,则可以完全读取文件。将内容记录到stdout或sticka。