如何使用Python验证具有转义引号的JSON字符串

huangapple go评论70阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年1月4日 00:33:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/59582073.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定