在.json
文件中有以下JSON数据:
[
{
"Type":"SET",
"routine":[
{
"ID":"1",
"InternalType":"Motorcycle",
"payload":"2"
},
{
"ID":"12",
"InternalType":"Chair"
}
]
},
{
"Type":"GET",
"routine":[
{
"ID":"1",
"InternalType":"Wheel"
},
{
"ID":"4",
"InternalType":"Car",
"payload":"6"
}
]
}
]
我试图按以下方式检查和解析数据:
#include<iostream>
#include<fstream>
#include"json.hpp"
using json = nlohmann::json;;
using namespace std;
int main (){
string pathToFile = "/absolute/path/to/my/exampledata.json";
ifstream streamOfFile(pathToFile);
if(!json::accept(streamOfFile)){
cout << "JSON NOT VALID!" << endl;
} else {
cout << "Nothing to complain about!" << endl;
}
try {
json allRoutines = json::parse(streamOfFile);
} catch (json::parse_error& error){
cerr << "Parse error at byte: " << error.byte << endl;
}
return 0;
}
我编译并运行它如下:
g++ myCode.cpp -o out
./out
Nothing to complain about!
Parse error at byte: 1
正如我所理解的函数json::accept()
,如果JSON
数据是有效的,它应该返回JSON
。https://json.nlohmann.me/api/basic_json/accept/
在我的例子中,您可以看到,accept()
函数在数据流上返回true,但在实际解析时抛出一个json::parse_error
。所以我想知道是否有人在我使用这两个函数时看到了一个错误,数据或者可以向我解释为什么它是那样的。
亲切的问候
发布于 2022-10-05 07:16:28
json::accept(streamOfFile)
从输入流一直读取到末尾。
json::parse(streamOfFile)
无法在输入流结束后读取。
这与JSON库无关,它是流的一个通用特性,一旦被读取,它们就会到达文件状态的末尾。
您可能希望将流重置为零文件位置,然后解析该文件。
streamOfFile.clear(); // Reset eof state
streamOfFile.seekg(0, ios::beg) // Seek to the begin of the file
json allRoutines = json::parse(streamOfFile);
https://stackoverflow.com/questions/73956788
复制相似问题