2

My Input string is like this:

std::string temp = "{\"key\":\""+ message + "\"}";

For Eg: message can be like this:

"Stack \n Overflow"

message can be anything. It can contain escape sequence characters also.

I expect this is a valid JSON and if I try to parse that JSON using below code:

Document document; 
document.Parse(temp.c_str());

document.parse is returning null.

I don't want to add one more \ before escape sequences. I just want to understand if there are any other ways to parse this JSON string using rapid JSON library in C++.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Akhilesh
  • 31
  • 6

1 Answers1

2

document.Parse returns null when the JSON you pass in to it is not valid. There is no substitute for creating valid JSON, and that means ensuring that the contents of message are properly escaped, particularly any " characters, control characters like line breaks, etc. You have to deal with it, not avoid it.

For example

#include <string>
#include <sstream>
#include <iomanip>

std::string jsonEscape(const std::string &s)
{
    std::ostringstream oss;
    for(char c : s)
    {
        switch (c)
        {
            case '"':  oss << "\\\""; break;
            case '\\': oss << "\\\\"; break;
            case '/':  oss << "\\/"; break;
            case '\b': oss << "\\b"; break;
            case '\f': oss << "\\f"; break;
            case '\r': oss << "\\r"; break;
            case '\n': oss << "\\n"; break;
            case '\t': oss << "\\t"; break;
            default:
                if ((c >= 0x00) && (c <= 0x1F))
                    oss << "\\u" << std::hex << std::noshowbase << std::nouppercase << std::setw(4) << std::setfill('0') << (int)c;
                else
                    oss << c;
                break;
        }
    }
    return oss.str();
}

std::string temp = "{\"key\": \"" + jsonEscape(message) + "\"}";

Or, you could simply use RapidJSON's own API to produce a valid JSON string, and to parse it afterwards (which would be redundant, since you would already have a Document):

Document document(kObjectType);

Value key;
key.SetString(StringRef(message.c_str(), message.length()));
document.AddMember("key", key, document.GetAllocator());

StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
document.Accept(writer);

std::string temp = buffer.GetString();
Top-Master
  • 7,611
  • 5
  • 39
  • 71
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770