How to deal with escape characters with JSON loads?

Question:

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)

Asked By: Willem van Houten

||

Answers:

Use double backslahes to escape quotes in the json:

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

or raw string literal:

search = r"""
[{"text":"Dolores Keane - "Craigie Hills" (1982)"}]
"""
Answered By: Guru Stron

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)'}])
Answered By: chepner

You can use json.dumps to see how the original object should be encoded into JSON:

>>> import json
>>> json.dumps([{"text":"Dolores Keane - "Craigie Hills" (1982)"}])
'[{"text": "Dolores Keane - \"Craigie Hills\" (1982)"}]'

and then confirm that json.loads can decode that same string:

>>> search = json.dumps([{"text":"Dolores Keane - "Craigie Hills" (1982)"}])
>>> json.loads(search)
[{'text': 'Dolores Keane - "Craigie Hills" (1982)'}]
Answered By: Samwise
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.