简体   繁体   English

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

[英]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.

相关问题 如何用转义引号操作字符串 - How to manipulate string with escaped quotes 如何从字符串中删除外国转义引号? Python - How to remove foreign escaped quotes from string? Python JSON 转储由单引号包围并包含转义单引号的字符串 - JSON Dump a string surrounded by single quotes and containing escaped single quotes 如何使用节点 js 或 python 将带有转义字符串的 json 解析为更小的 json - How to parse a json with escaped string into smaller json with node js or python 使用re在python中找到引号中的项目,而不是转义的引号 - Finding items in quotes, but not escaped quotes, in python using re 使用正则表达式将 Python 中的转义双引号替换为单引号 - Replace escaped double quotes to single quotes in Python using regex 如何在python2.7中的字符串中嵌入一个字符串,其中已经转义了引号? - How to embed a string within a string in python2.7, that has escaped quotes in it? 如何从包含转义双引号的 JSON 对象创建 Python dict? - How can I create a Python dict from a JSON object that contains escaped double quotes? 如何将单引号传递给 python 中的 json 字符串? - How to pass single quotes to json string in python? Python如何将单引号转换为双引号以格式化为json字符串 - Python how convert single quotes to double quotes to format as json string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM