Skip to content

[Bug]: A string ending in a backslash loses it and gains a quote during repair #247

Closed

Description

@jbrown9513

Version of the library

Tested on 0.64.2 (commit f13a96b). I read the same code on main at f0eff1e (0.64.4) but did not run it there.

Describe the bug

When a document needs repair, a string that ends in an escaped backslash is corrupted. This also happens with skip_json_loads=True. A truncated Windows path is the plain case: the value comes back with a " where the backslash was. In an array, the closing ] gets pulled into the string too.

The even-run branch in _normalize_escape_sequence excludes a following quote:

if run_length % 2 == 0 and next_char != active_rstring_delimiter:

So \\" falls to the generic branch, whose while loop reads that quote as an escaped one:

if char in [active_rstring_delimiter, "t", "n", "r", "b", "\\"]:
escape_seqs = {"t": "\t", "n": "\n", "r": "\r", "b": "\b"}
_replace_trailing_backslash(state, escape_seqs.get(char, char))
self.index += 1
next_char = self.get_char_at()
while (
next_char
and state.string_acc
and state.string_acc[-1] == "\\"
and next_char in [active_rstring_delimiter, "\\"]
):
_replace_trailing_backslash(state, next_char)
self.index += 1
next_char = self.get_char_at()
return True, next_char

I don't know whether that exclusion is there for doubly escaped quotes, so I haven't suggested a patch.

How to reproduce

from json_repair import repair_json

repair_json('{"path": "C:\\\\"', return_objects=True)
# {'path': 'C:"'}

repair_json('["R\\\\"]', return_objects=True, skip_json_loads=True)
# ['R"]']

The JSON text in the first call is {"path": "C:\\", cut off before the closing brace.

Expected behavior

The backslash stays and the quote closes the string, as json.loads reads the complete text: {'path': 'C:\\'} and ['R\\'].

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions