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
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();
}
精彩评论