mirror of
https://github.com/yhirose/cpp-peglib.git
synced 2024-12-22 20:05:31 +00:00
Fixed problem with JSON invalid characters
This commit is contained in:
parent
47e51d3651
commit
e12ab41b40
@ -2,6 +2,8 @@
|
|||||||
#include "peglib.h"
|
#include "peglib.h"
|
||||||
#include <cstdio>
|
#include <cstdio>
|
||||||
#include <functional>
|
#include <functional>
|
||||||
|
#include <iomanip>
|
||||||
|
#include <sstream>
|
||||||
|
|
||||||
using namespace httplib;
|
using namespace httplib;
|
||||||
using namespace std;
|
using namespace std;
|
||||||
@ -238,6 +240,20 @@ body {
|
|||||||
</html>
|
</html>
|
||||||
)";
|
)";
|
||||||
|
|
||||||
|
// https://stackoverflow.com/questions/7724448/simple-json-string-escape-for-c/33799784#33799784
|
||||||
|
std::string escape_json(const std::string &s) {
|
||||||
|
std::ostringstream o;
|
||||||
|
for (auto c : s) {
|
||||||
|
if (c == '"' || c == '\\' || ('\x00' <= c && c <= '\x1f')) {
|
||||||
|
o << "\\u"
|
||||||
|
<< std::hex << std::setw(4) << std::setfill('0') << (int)c;
|
||||||
|
} else {
|
||||||
|
o << c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return o.str();
|
||||||
|
}
|
||||||
|
|
||||||
function<void (size_t, size_t, const string&)> makeJSONFormatter(string& json)
|
function<void (size_t, size_t, const string&)> makeJSONFormatter(string& json)
|
||||||
{
|
{
|
||||||
auto init = make_shared<bool>(true);
|
auto init = make_shared<bool>(true);
|
||||||
@ -249,7 +265,7 @@ function<void (size_t, size_t, const string&)> makeJSONFormatter(string& json)
|
|||||||
json += "{";
|
json += "{";
|
||||||
json += R"("ln":)" + to_string(ln) + ",";
|
json += R"("ln":)" + to_string(ln) + ",";
|
||||||
json += R"("col":)" + to_string(col) + ",";
|
json += R"("col":)" + to_string(col) + ",";
|
||||||
json += R"("msg":")" + msg + R"(")";
|
json += R"("msg":")" + escape_json(msg) + R"(")";
|
||||||
json += "}";
|
json += "}";
|
||||||
*init = false;
|
*init = false;
|
||||||
};
|
};
|
||||||
@ -321,13 +337,8 @@ int run_server(int port, const vector<char>& syntax, const vector<char>& source)
|
|||||||
const auto& codeText = req.get_param_value("code");
|
const auto& codeText = req.get_param_value("code");
|
||||||
shared_ptr<peg::Ast> ast;
|
shared_ptr<peg::Ast> ast;
|
||||||
if (parse_code(codeText, peg, codeResult, ast)) {
|
if (parse_code(codeText, peg, codeResult, ast)) {
|
||||||
astResult = peg::ast_to_s(ast);
|
astResult = escape_json(peg::ast_to_s(ast));
|
||||||
astResult = replace_all(astResult, "\n", "\\n");
|
astResultOptimized = escape_json(peg::ast_to_s(peg::AstOptimizer(true).optimize(ast)));
|
||||||
astResult = replace_all(astResult, "\"", "%22");
|
|
||||||
|
|
||||||
astResultOptimized = peg::ast_to_s(peg::AstOptimizer(true).optimize(ast));
|
|
||||||
astResultOptimized = replace_all(astResultOptimized, "\n", "\\n");
|
|
||||||
astResultOptimized = replace_all(astResultOptimized, "\"", "%22");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user