[英]How to validate a JSON string with escaped quotes using Python
I am using json.loads to parse a JSON string.我正在使用 json.loads 来解析 JSON 字符串。 However, it identifies the string as invalid JSON when it contains escaped double quotes.但是,当字符串包含转义的双引号时,它会将字符串标识为无效的 JSON。 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):由于反斜杠本身是一个转义字符,您需要对其进行转义,或者使用原始字符串(仅带有r
前缀):
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
:它的\\
需要转义以生成有效的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.