.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(),它應該回傳的函式。https://json.nlohmann.me/api/basic_json/accept/trueJSON
在我的例子中,您可以看到,該accept()函式在資料流上回傳 true,但在實際決議時拋出 a json::parse_error。所以我想知道是否有人碰巧看到我在使用這兩個函式、資料時出現錯誤,或者可以向我解釋為什么它會這樣。
親切的問候
uj5u.com熱心網友回復:
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://www.uj5u.com/yidong/512185.html
上一篇:從自定義XBRL檔案設定背景關系
下一篇:快速決議xml檔案
