抛出 'nlohmann::detail::parse_error' 实例后调用终止

0 c++ json nlohmann-json

terminate called after throwing an instance of 'nlohmann::detail::parse_error'
  what():  [json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing object key - unexpected end of input; expected string literal
Run Code Online (Sandbox Code Playgroud)

尝试使用data.jsonC++ 从本地文件解析 JSON。

代码如下:

#include <iostream>
#include <stdio.h>
#include <string>
#include <fstream>
#include "json.hpp"
using namespace std;
using json = nlohmann::json;
int main() {
  string text;
  int x;
  string jsonguy[5];
  ifstream i("data.json");
  i >> text;
  json data = json::parse(text);
  i.close();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我有本地进口的 Nlohmann json.hpp。它继续报告这些错误,我该如何修复它?

Rem*_*eau 5

在语句 中i >> text;operator>>从文件流中读取单个空格分隔的标记并将其保存到text.

然后您尝试解析该单个令牌text,而不是整个文件。因此,如果 JSON 数据中存在任何空格,您最终会将无效的 JSON 传递给parse(),从而出现错误。

例如,如果 JSON 如下所示:

{
  "key": "value"
}
Run Code Online (Sandbox Code Playgroud)

该语句i >> text仅提取内容{,不提取其他内容。

要解决此问题,请删除该i >> text语句并将i其自身传递给parse(),例如:

#include <iostream>
#include <fstream>
#include "json.hpp"

using json = nlohmann::json;

int main() {
  std::ifstream i("data.json");
  json data = json::parse(i);
  i.close();
  // use data as needed...
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

文档parse()

// (1)
template<typename InputType>
static basic_json parse(InputType&& i,
                        const parser_callback_t cb = nullptr,
                        const bool allow_exceptions = true,
                        const bool ignore_comments = false);
Run Code Online (Sandbox Code Playgroud)

从兼容输入反序列化。

InputType

兼容的输入,例如:

  • 一个std::istream物体<--
  • 一个FILE指针
  • C 风格的字符数组
  • 指向以空字符结尾的单字节字符字符串的指针
  • Astd::string
  • 一个对象,并obj为其生成一对有效的迭代器。begin(obj)end(obj)

如果您确实想将文件内容解析为std::string,请参阅如何将整个文件读入 C++ 中的 std::string ?