2
2
#include " peglib.h"
3
3
#include < cstdio>
4
4
#include < functional>
5
+ #include < iomanip>
6
+ #include < sstream>
5
7
6
8
using namespace httplib ;
7
9
using namespace std ;
@@ -238,6 +240,20 @@ body {
238
240
</html>
239
241
)" ;
240
242
243
+ // https://stackoverflow.com/questions/7724448/simple-json-string-escape-for-c/33799784#33799784
244
+ std::string escape_json (const std::string &s) {
245
+ std::ostringstream o;
246
+ for (auto c : s) {
247
+ if (c == ' "' || c == ' \\ ' || (' \x00 ' <= c && c <= ' \x1f ' )) {
248
+ o << " \\ u"
249
+ << std::hex << std::setw (4 ) << std::setfill (' 0' ) << (int )c;
250
+ } else {
251
+ o << c;
252
+ }
253
+ }
254
+ return o.str ();
255
+ }
256
+
241
257
function<void (size_t , size_t , const string&)> makeJSONFormatter (string& json)
242
258
{
243
259
auto init = make_shared<bool >(true );
@@ -249,7 +265,7 @@ function<void (size_t, size_t, const string&)> makeJSONFormatter(string& json)
249
265
json += " {" ;
250
266
json += R"( "ln":)" + to_string (ln) + " ," ;
251
267
json += R"( "col":)" + to_string (col) + " ," ;
252
- json += R"( "msg":")" + msg + R"( ")" ;
268
+ json += R"( "msg":")" + escape_json ( msg) + R"( ")" ;
253
269
json += " }" ;
254
270
*init = false ;
255
271
};
@@ -321,13 +337,8 @@ int run_server(int port, const vector<char>& syntax, const vector<char>& source)
321
337
const auto & codeText = req.get_param_value (" code" );
322
338
shared_ptr<peg::Ast> ast;
323
339
if (parse_code (codeText, peg, codeResult, ast)) {
324
- astResult = peg::ast_to_s (ast);
325
- astResult = replace_all (astResult, " \n " , " \\ n" );
326
- astResult = replace_all (astResult, " \" " , " %22" );
327
-
328
- astResultOptimized = peg::ast_to_s (peg::AstOptimizer (true ).optimize (ast));
329
- astResultOptimized = replace_all (astResultOptimized, " \n " , " \\ n" );
330
- astResultOptimized = replace_all (astResultOptimized, " \" " , " %22" );
340
+ astResult = escape_json (peg::ast_to_s (ast));
341
+ astResultOptimized = escape_json (peg::ast_to_s (peg::AstOptimizer (true ).optimize (ast)));
331
342
}
332
343
}
333
344
0 commit comments