英文:
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 (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")
英文:
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!
答案1
得分: 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}'
英文:
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}'
答案2
得分: 1
这是需要转义的 \
以生成有效的 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")
输出:
initial strings given -
{ "name":"Nickname \"John\" Doe", "age":31, "Salary":25000}
Is valid json? true
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论