首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用nlohmann的C++库解析有效JSON数据中的错误

用nlohmann的C++库解析有效JSON数据中的错误
EN

Stack Overflow用户
提问于 2022-10-05 06:55:25
回答 1查看 152关注 0票数 0

.json文件中有以下JSON数据:

代码语言:javascript
运行
复制
[
   {
      "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"
         }
      ]
   }
]

我试图按以下方式检查和解析数据:

代码语言:javascript
运行
复制
  #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;
  }

我编译并运行它如下:

代码语言:javascript
运行
复制
g++ myCode.cpp -o out
./out
Nothing to complain about!
Parse error at byte: 1

正如我所理解的函数json::accept(),如果JSON数据是有效的,它应该返回JSONhttps://json.nlohmann.me/api/basic_json/accept/

在我的例子中,您可以看到,accept()函数在数据流上返回true,但在实际解析时抛出一个json::parse_error。所以我想知道是否有人在我使用这两个函数时看到了一个错误,数据或者可以向我解释为什么它是那样的。

亲切的问候

EN

Stack Overflow用户

回答已采纳

发布于 2022-10-05 07:16:28

json::accept(streamOfFile)从输入流一直读取到末尾。

json::parse(streamOfFile)无法在输入流结束后读取。

这与JSON库无关,它是流的一个通用特性,一旦被读取,它们就会到达文件状态的末尾。

您可能希望将流重置为零文件位置,然后解析该文件。

代码语言:javascript
运行
复制
streamOfFile.clear();            // Reset eof state
streamOfFile.seekg(0, ios::beg)  // Seek to the begin of the file
json allRoutines = json::parse(streamOfFile);
票数 5
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73956788

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档