Escapes characters in a string to be JSON safe. Parameters: s (str): The input string to be escaped. Returns: str: The escaped string, safe for JSON encoding.
(s)
| 150 | return text.encode('ascii', errors='ignore').decode('ascii') |
| 151 | |
| 152 | def escape_json_string(s): |
| 153 | """ |
| 154 | Escapes characters in a string to be JSON safe. |
| 155 | |
| 156 | Parameters: |
| 157 | s (str): The input string to be escaped. |
| 158 | |
| 159 | Returns: |
| 160 | str: The escaped string, safe for JSON encoding. |
| 161 | """ |
| 162 | # Replace problematic backslash first |
| 163 | s = s.replace('\\', '\\\\') |
| 164 | |
| 165 | # Replace the double quote |
| 166 | s = s.replace('"', '\\"') |
| 167 | |
| 168 | # Escape control characters |
| 169 | s = s.replace('\b', '\\b') |
| 170 | s = s.replace('\f', '\\f') |
| 171 | s = s.replace('\n', '\\n') |
| 172 | s = s.replace('\r', '\\r') |
| 173 | s = s.replace('\t', '\\t') |
| 174 | |
| 175 | # Additional problematic characters |
| 176 | # Unicode control characters |
| 177 | s = re.sub(r'[\x00-\x1f\x7f-\x9f]', lambda x: '\\u{:04x}'.format(ord(x.group())), s) |
| 178 | |
| 179 | return s |
| 180 | |
| 181 | class CustomHTML2Text(HTML2Text): |
| 182 | def __init__(self, *args, **kwargs): |
no outgoing calls
no test coverage detected
searching dependent graphs…