简体   繁体   中英

How to validate a JSON string with escaped quotes using Python

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 (ie 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!

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}'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM