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
Trying to use JSON parsing from local data.json file with C++.
Code is as follows:
#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;
}
I have the Nlohmann json.hpp imported locally. It continues to report these errors, how do I fix it?
In the statement
i >> text;,operator>>reads a single whitespace-delimited token from the file stream and saves it intotext.And then you are trying to parse that single-token
text, not the entire file. So, if there is any whitespace present in the JSON data, you would end up passing invalid JSON toparse(), hence the error.For example, if the JSON looks like this:
The statement
i >> textwill extract only{and nothing else.To fix this, get rid of the
i >> textstatement and just passiitself toparse()instead, eg:The
parse()documentation says:If you really want to parse the file content as a
std::string, see How do I read an entire file into a std::string in C++?