hmmmmmm
hmmmmmm

Reputation: 321

Rapidjson returning wrong data

The json I receive:

{
  "status": "success",
  "data": {
    "user_id": "acv",
    "user_type": "individual",
    "email": "[email protected]",
    "user_name": "xyz",
    "user_shortname": "xx",
    "broker": "zzzz",
    "exchanges": [
      "aaa",
      "cvv",
      "bbb",
      "sss",
      "MF",
      "eee"
    ],
    "products": [
      "CNC",
      "NRML",
      "MIS",
      "BO",
      "CO"
    ],
    "order_types": [
      "MARKET",
      "LIMIT",
      "SL",
      "SL-M"
    ],
    "avatar_url": "",
    "meta": {
      "demat_consent": "consent"
    }
  }
}

I have a function that parses received json: (rj is nothing but a namespace alias declared like using rj=rapidjson;)

rj::Value& parser(...){
    rj::Document data;

    data.Parse("data received passed as const char*");

    //------can access correct email string here------
    std::string debugstr = data["data"].GetObject()["email"].GetString();


    return data["data"];

  }
   

I use it like:

void func1(){
    rj::Value::Object res = parser().GetObject();
 
    //-----this string for some reason is "\003"------
    std::string debugstr = res["email"].GetString();
}

Why is this happening? I've ran this multiple times. I'm on Linux using latest rapidjson.

Similar to the email field, I cannot access other values correctly as well. Only one (broker) is correct while others are either empty strings or random garbage.

Upvotes: 0

Views: 812

Answers (2)

Per Ghosh
Per Ghosh

Reputation: 533

The root document in rapidjson differs from other json values. The Document has the allocator. If this object is deleted then all json values connected to that document is destroyed. RapidJSON is designed to be fast, and this is one of the trade-offs that this library has done to improve speed.

Returning a reference to variable from function where the variable is created will always generate errors.

You could return the complete document in a shared pointer std::shared_ptr.

Here are one tutorial for rapidjson and two others.

Upvotes: 1

john
john

Reputation: 87944

I'm not very familar with this library but it seems likely the problem is here

rj::Value& parser(...){
    ...
    return data["data"];
}

You are returning a reference to the internals of the data variable. But the data variable is local to parser and will be destroyed when parser is exited. So you end up with a reference to an object which has been destroyed. That explains the garbage values.

Try returning a value instead

rj::Value parser(...){

(I'm assuming this is possible with the rapidjson library).

Upvotes: 2

Related Questions