开发者

I don't want JSON to escape apostrophes in C++. How to fix this?

开发者 https://www.devze.com 2023-02-11 04:32 出处:网络
I\'ve encountered a bit of a problem with JSON (libjson 6). In a chat messenger I am making, there is a conflict between the server (which was made by other people) and the desktop client. My client\'

I've encountered a bit of a problem with JSON (libjson 6). In a chat messenger I am making, there is a conflict between the server (which was made by other people) and the desktop client. My client's JSON strings always have apostrophes escaped, even though I always use 开发者_开发知识库quotes to delimit strings. The server, on the other hand, doesn't expect apostrophes to be escaped, which leads to situations where my client sends \' which obviously creates problems for the server's parser.

The only way for me to solve this, is by making my program stop escaping apostrophes in JSON messages. However, after searching on Google and in the documentation, I haven't found anything. Can somebody tell me how to do this?


You can remove the escapes before the apostrophes.

If you never have escaped escapes before an apostrophe (e.g. \\' meaning "escaped-escape and unescaped apostrophe") or your library always escapes them, simply replace all \' with '. There are various string replace functions, but this is a simple case:

bool is_broken_escaped_apos(std::string const &data, std::string::size_type n) {
  return n + 2 <= data.size()
     and data[n] == '\\'
     and data[n+1] == '\'';
}
void fix_broken_escaped_apos(std::string &data) {
  for (std::string::size_type n = 0; n != data.size(); ++n) {
    if (is_broken_escaped_apos(data, n)) {
      data.replace(n, 2, 1, '\'');
    }
  }
}

Otherwise, you'll have to parse a subset of the string escapes, which is more involved, but not hard.

0

精彩评论

暂无评论...
验证码 换一张
取 消