Search code examples
c++jsonrapidjson

C++ RapidJSON parse a JSON object wrapped in a callback function


i'm trying to parse a JSON response from Yahoo API using RapidJSON library in C++ , and this response is wrapped in a callback method. This is the response i'm getting

YAHOO.util.ScriptNodeDataSource.callbacks({"ResultSet":{"Query":"AMZN","Result":[{"symbol":"AMZN","name":"Amazon.com, Inc.","exch":"NMS","type":"S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"AMZN.MX","name":"Amazon.com, Inc.","exch":"MEX","type":"S","exchDisp":"Mexico","typeDisp":"Equity"}]}});

If i feed this JSON response directly to RapidJSON like this it cannot parse it.

rapidjson::Document json_doc;

if (json_doc.Parse(fetched_data.c_str()).HasParseError()) {
        continue;
}

So what is the method to parse the JSON with this callback function portion YAHOO.util.ScriptNodeDataSource.callbacks other than the obvious way to delete this substring altogether.


Solution

  • you can psuedo-null the ); part and give a pointer to just after the callback part:

    size_t pos = std::string("YAHOO.util.ScriptNodeDataSource.callbacks(").size();
    std::string stringifiedJSON = "YAHOO.util.ScriptNodeDataSource.callbacks({"ResultSet": /*...*/ });"
    str[str.size() - 2] = 0; // null terminate exactly on ");"
    const char* ptr = stringifiedJSON.data();
    ptr += pos;
    json::Document doc;
    doc.parse(ptr);
    str[str.size() - 2] = ')'; //revert the string back;