如何在Python定义的字符串中保留转义引号
解决Python中保留字符串转义双引号并生成指定POST Body的方法
方法一:手动双重转义
如果要直接定义带有转义双引号的字符串,需要对反斜杠进行双重转义(Python中单个反斜杠是转义符,要表示实际的反斜杠需写两个):
a = "{\\\"key1\\\":\\\"value1\\\",\\\"key2\\\":\\\"value2\\\"}" print(a) # 输出:"{\"key1\":\"value1\",\"key2\":\"value2\"}"
方法二:使用原始字符串(Raw String)
在字符串前加r前缀,Python会将字符串中的反斜杠视为普通字符,无需额外转义:
a = r"{\"key1\":\"value1\",\"key2\":\"value2\"}" print(a) # 输出:"{\"key1\":\"value1\",\"key2\":\"value2\"}"
方法三:用json模块自动处理嵌套JSON(推荐)
手动转义容易出错,针对你需要的POST Body,更高效的方式是先构建多层字典,再通过json.dumps()自动处理转义:
import json # 构建expression.value对应的内层字典 value_dict = { "type": "query", "e": "account", "variable": "parameterReference1", "condition": { "type": "boolean_combination", "operator": "and", "sub_conditions": [ { "type": "comparison", "lhs": { "type": "property", "property_path": ["accountOrganization", "industry"] }, "operator": "equals", "rhs": ["finance"] } ] } } # 构建完整的POST Body字典 post_body = { "name": "test24", "description": "test1", "schema": {"name": "schema_name"}, "expression": { "format": "json", "type": "blah", "value": json.dumps(value_dict) # 将内层字典转为带转义的JSON字符串 }, "type": "sd" } # 生成最终的POST Body字符串 final_post_body = json.dumps(post_body) print(final_post_body)
运行后会输出你需要的格式:
{"name":"test24","description":"test1","schema":{"name":"schema_name"},"expression":{"format":"json","type":"blah","value":"{\"type\":\"query\",\"e\":\"account\",\"variable\":\"parameterReference1\",\"condition\":{\"type\":\"boolean_combination\",\"operator\":\"and\",\"sub_conditions\":[{\"type\":\"comparison\",\"lhs\":{\"type\":\"property\",\"property_path\":[\"accountOrganization\",\"industry\"]},\"operator\":\"equals\",\"rhs\":[\"finance\"]]}}}","type":"sd"}
内容的提问来源于stack exchange,提问作者rishabh
相关产品推荐
相关产品推荐

