skip to Main Content
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)

3

Answers


  1. 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)"}]
    """
    
    Login or Signup to reply.
  2. 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)'}])
    
    Login or Signup to reply.
  3. 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)'}]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search