| 58 | } |
| 59 | |
| 60 | std::string escapeNewlinesAndTabsWithinStringLiterals(std::string const& _json) |
| 61 | { |
| 62 | std::stringstream fixed; |
| 63 | bool inQuotes = false; |
| 64 | for (size_t i = 0; i < _json.size(); ++i) |
| 65 | { |
| 66 | char c = _json[i]; |
| 67 | |
| 68 | // Originally we had just this here: |
| 69 | // if (c == '"' && (i == 0 || _json[i - 1] != '\\')) |
| 70 | // inQuotes = !inQuotes; |
| 71 | // However, this is not working if the escape character itself was escaped. e.g. "\n\r'\"\\". |
| 72 | |
| 73 | if (c == '"') |
| 74 | { |
| 75 | size_t backslashCount = 0; |
| 76 | size_t j = i; |
| 77 | while (j > 0 && _json[j - 1] == '\\') |
| 78 | { |
| 79 | backslashCount++; |
| 80 | j--; |
| 81 | } |
| 82 | if (backslashCount % 2 == 0) |
| 83 | { |
| 84 | inQuotes = !inQuotes; |
| 85 | fixed << c; |
| 86 | continue; |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | if (inQuotes) |
| 91 | { |
| 92 | if (c == '\n') |
| 93 | fixed << "\\n"; |
| 94 | else if (c == '\t') |
| 95 | fixed << "\\t"; |
| 96 | else |
| 97 | fixed << c; |
| 98 | } |
| 99 | else |
| 100 | fixed << c; |
| 101 | } |
| 102 | return fixed.str(); |
| 103 | } |
| 104 | |
| 105 | } // end anonymous namespace |
| 106 |
no test coverage detected