Search code examples
pythonjsonescaping

How to deal with escape characters with JSON loads?


search = """
[{"text":"Dolores Keane - \"Craigie Hills\" (1982)"}]
"""
print(loads(search)) # Returns Error
print(search.replace('"',"'")) # Turns all double quotes to single quotes, both the escaped and non escaped ones

Here's my issues: I just don't know how to load this sort of strings into JSON. Any tips? I tried a billion things. Tried repr(search), etc, nothing works.

EDIT: For those who wonder about the question: the issue is that the string has both double quotes that indicate a dictionary item or key (") and double quotes with a backslash before them that indicate part of a string ("). I was not able to load the string, correctly differentiating between the two.

In the answers, I got two solutions: using a rawstring, and dumping before loading.

The error: json.decoder.JSONDecodeError: Expecting ',' delimiter: line 2 column 28 (char 28)


Solution

  • You forgot to escape the \ so that you have literal backslashes in the JSON. Use a raw string literal

    search = r"""
    [{"text":"Dolores Keane - \"Craigie Hills\" (1982)"}]
    """
    

    or let json.dumps produce the JSON in the first place:

    search = json.dumps([dict(text='Dolores Keane - "Craigie Hills" (1982)'}])