1

I am using json.loads to parse a JSON string. However, it identifies the string as invalid JSON when it contains escaped double quotes. Since the string itself is valid, how could I parse it correctly without modifying the input string (i.e. using \\" instead of \"). Here is my code:

import json 

a = '{"name":"Nickname \"John\" Doe", "age":31, "Salary":25000}'

print ("initial strings given - \n", a) 

try: 
    json_object1 = json.loads(a) 

    print ("Is valid json? true") 

except ValueError as e: 
    print ("Is valid json? false") 

Thanks!

2
  • 1
    But aren't all of the quote marks in that string effectively escaped, regardless of whether a "\" precedes them? '"\"' evaluates to the same string as '""'. Commented Jan 3, 2020 at 16:37
  • 1
    Letting json generate the JSON from a dict would be simpler: a = json.dumps(dict(name='Nickname "John" Doe', age=31, Salary=25000)). Commented Jan 3, 2020 at 16:40

2 Answers 2

4

Since the backslash itself is an escape character, you need to either escape it, or use a raw string (simply with the r prefix):

a = '{"name":"Nickname \\"John\\" Doe", "age":31, "Salary":25000}'

or

a = r'{"name":"Nickname \"John\" Doe", "age":31, "Salary":25000}'
Sign up to request clarification or add additional context in comments.

Comments

1

Its the \ that need escaping to make valid json:

#soJsonEscapeQuotes

import json 

a = '{"name":"Nickname \\"John\\" Doe", "age":31, "Salary":25000}'

print ("initial strings given - \n", a) 

try: 
    json_object1 = json.loads(a) 

    print ("Is valid json? true") 

except ValueError as e: 
    print ("Is valid json? false")

Output:

initial strings given - 
 {"name":"Nickname \"John\" Doe", "age":31, "Salary":25000}
Is valid json? true

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.