0

I am trying to parse a json file below:


    [
      {
        "date": "Mon 24 Dec 7:47:37 2018",
        "toRecipient": "Vinny",
        "subject": "Hi Vinny",
        "body": "This is Tony",
        "fromRecipient": "Tony"
      },
      
      {
        "date": "Mon 24 Dec 7:47:38 2018",
        "toRecipient": "Vinny",
        "subject": "Hi Vinny2",
        "body": "This is Tony 2",
        "fromRecipient": "Tony"
      },
    etc...

And this is my function for parsing:

            MessageLibrary::MessageLibrary(string jsonFileName) {
            Json::Reader reader;
            Json::Value root;
            std::ifstream json(jsonFileName.c_str(), std::ifstream::binary);
            bool parseSuccess = reader.parse(json, root, false);
        
            if (parseSuccess) {
                Json::Value::Members mbr = root.getMemberNames();
                for(vector<string>::const_iterator i = mbr.begin(); i!= mbr.end(); i++) {
                    Json::Value jsonMessage = root[*i];
        
                    string date = jsonMessage["date"].asString();
                    string toRecipient = jsonMessage["toRecipient"].asString();
                    string subject = jsonMessage["subject"].asString();
                    string body = jsonMessage["body"].asString();
                    string fromRecipient = jsonMessage["fromRecipient"].asString();
        
                    // create Message objects from parse
                    Message *message = new Message(toRecipient, fromRecipient, subject, body, date);
                    messages[*i] = *message;
}

The error seems to be coming when I call Json::Value::Members mbr = root.getMemberNames(); and I'm not sure how to get around this.

terminate called after throwing an instance of 'Json::LogicError'
what(): in Json::Value::getMemberNames(), value must be objectValue Aborted (core dumped)

Tony
  • 77
  • 3
  • 12

1 Answers1

0

Was able to realize thanks to user xyz347 my entire JSON is an array and needed to loop through it differently like so:

    if (parseSuccess) {
            for(Json::Value::ArrayIndex i = 0; i != root.size(); i++) {

                string date = root[i]["date"].asString();
                string toRecipient = root[i]["toRecipient"].asString();
                string subject = root[i]["subject"].asString();
                string body = root[i]["body"].asString();
                string fromRecipient = root[i]["fromRecipient"].asString();

                // create Message objects from parse
                Message *message = new Message(toRecipient, fromRecipient, subject, body, date);
                // messages[*i] = *message;    // this doesn't work though
            }
Tony
  • 77
  • 3
  • 12