Skip to content

Commit e12ab41

Browse files
committed
Fixed problem with JSON invalid characters
1 parent 47e51d3 commit e12ab41

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

lint/server.cc

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
#include "peglib.h"
33
#include <cstdio>
44
#include <functional>
5+
#include <iomanip>
6+
#include <sstream>
57

68
using namespace httplib;
79
using namespace std;
@@ -238,6 +240,20 @@ body {
238240
</html>
239241
)";
240242

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+
241257
function<void (size_t, size_t, const string&)> makeJSONFormatter(string& json)
242258
{
243259
auto init = make_shared<bool>(true);
@@ -249,7 +265,7 @@ function<void (size_t, size_t, const string&)> makeJSONFormatter(string& json)
249265
json += "{";
250266
json += R"("ln":)" + to_string(ln) + ",";
251267
json += R"("col":)" + to_string(col) + ",";
252-
json += R"("msg":")" + msg + R"(")";
268+
json += R"("msg":")" + escape_json(msg) + R"(")";
253269
json += "}";
254270
*init = false;
255271
};
@@ -321,13 +337,8 @@ int run_server(int port, const vector<char>& syntax, const vector<char>& source)
321337
const auto& codeText = req.get_param_value("code");
322338
shared_ptr<peg::Ast> ast;
323339
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)));
331342
}
332343
}
333344

0 commit comments

Comments
 (0)