| 18 | #include <string> |
| 19 | |
| 20 | std::string EncodeJSONString(const std::string& in) { |
| 21 | static const char* hex_digits = "0123456789abcdef"; |
| 22 | std::string out; |
| 23 | out.reserve(in.length() * 1.2); |
| 24 | for (std::string::const_iterator it = in.begin(); it != in.end(); ++it) { |
| 25 | char c = *it; |
| 26 | if (c == '\b') |
| 27 | out += "\\b"; |
| 28 | else if (c == '\f') |
| 29 | out += "\\f"; |
| 30 | else if (c == '\n') |
| 31 | out += "\\n"; |
| 32 | else if (c == '\r') |
| 33 | out += "\\r"; |
| 34 | else if (c == '\t') |
| 35 | out += "\\t"; |
| 36 | else if (0x0 <= c && c < 0x20) { |
| 37 | out += "\\u00"; |
| 38 | out += hex_digits[c >> 4]; |
| 39 | out += hex_digits[c & 0xf]; |
| 40 | } else if (c == '\\') |
| 41 | out += "\\\\"; |
| 42 | else if (c == '\"') |
| 43 | out += "\\\""; |
| 44 | else |
| 45 | out += c; |
| 46 | } |
| 47 | return out; |
| 48 | } |
| 49 | |
| 50 | void PrintJSONString(const std::string& in) { |
| 51 | std::string out = EncodeJSONString(in); |