Search code examples
c++rapidjson

assert is failing for rapidJson


I am trying to parse json data in c++ using RapidJson. I dont know where am I doing wrong but my assert is failing. When I try to debug its showing sigabrt when it runs the line assert. Community I appreciate your insights. Thanks for answering this naive question.

#include <iostream>
#include <assert.h>
#include "hpdf.h"
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include <rapidjson/istreamwrapper.h>
#include <fstream>

int main() {

    std::ifstream ifs("/home/is/..../test.json");
    rapidjson::IStreamWrapper isw(ifs);

    rapidjson::Document document;
    document.ParseStream(isw);


    assert(document.IsObject());

    rapidjson::Value::MemberIterator hello = document.FindMember("timeStamp");
    std::string vali = document["timestamp"].GetString();
    std::cout << vali << std::endl;

    return 0;

}

I tried using rapidJson filestream also but again it failed in the same line.

[
  {
    "timeStamp": "...",
    "alertType": "...",
    "instanceId": 8

   }
  ]

Solution

  • Read more about JSON.

    Your input document (starting with a [) is a JSON array containing a single JSON object.

    I recommend using document.GetType() then have different processing on its result (perhaps with a switch).

    So it is normal that document.IsObject() is false. For your input document.IsArray() should be true and your JSON object inside that array is accessible thru document[0]