Ondra
Ondra

Reputation: 3180

JSONify string in C++

In my program I need to output simle JSON data. I looked at many libraries for JSON in c++, they are too complex for my task. Is there some easier way, how to create JSON-safe string from any c++ string?

string s = "some potentially dangerous string";
cout << "{\"output\":\"" << convert_string(s) << "\"}";

How would function convert_string(string s) look like?

thanks

Upvotes: 2

Views: 6042

Answers (1)

etarion
etarion

Reputation: 17141

If your data is in UTF-8, per the string graph on http://json.org/:

#include <sstream>
#include <string>
#include <iomanip>
std::string convert_string(std::string s) {
    std::stringstream ss;
    for (size_t i = 0; i < s.length(); ++i) {
        if (unsigned(s[i]) < '\x20' || s[i] == '\\' || s[i] == '"') {
            ss << "\\u" << std::setfill('0') << std::setw(4) << std::hex << unsigned(s[i]);
        } else {
            ss << s[i];
        }
    } 
    return ss.str();
} 

Upvotes: 4

Related Questions