Search code examples
c++jsonstdmaprapidjson

Add values to map using rapidjson


I get a raw json string

{"vehicle": {"brand": "zonda","color": "blue"},"username": {"brand": "doyota","color": "red"}}

from a get call i make.

I read that rapidjson is the best way to parse a json string in cpp.

So I tried doing something like this:

const char* json = data.c_str();
rapidjson::Document document;
if (document.Parse(json).HasParseError()) {

    cout << "has parse error" << endl;

    return 1;
}
else {
    assert(document.IsObject());
}

Here it says that the json has a parse error. Any idea why this could be?

Also once I am able to parse the values I want to add them as key value pairs to a standard map. Could anyone point me in the right direction to proceed with this?


Solution

  • This gave me no error:

    #include <iostream>
    #include "rapidjson/document.h"
    #include "rapidjson/error/en.h"
    
    using namespace rapidjson;
    
    int main() {
        Document d;
        std::string json = R"raw({"vehicle": {"brand": "zonda","color": "blue"},"username": {"brand": "doyota","color": "red"}})raw";
    
        if (d.Parse(json.c_str()).HasParseError()) {
            std::cout << "has error\n";
        } else {
            std::cout << "no error\n";
        }
    }
    

    Tried C++11 - C++20 and it all seems fine. My guess is that you've got some non UTF8 character in the data.