我有一个 Python 脚本,它构建了一些 JavaScript,以 JSON 信封发送到浏览器。我想转义 JavaScript 字符串并用单引号将它们分隔开。我不能使用 json.dumps
,因为它像 JSON 规范要求的那样使用双引号作为分隔符。
Python 中有 JavaScript 字符串转义方法吗?
例子
def logIt(self, str):
#todo: need to escape str here
cmd = "console.log('%(text)s');" % { 'text': str}
json.dumps({ "script": cmd })
所以 logIt('example text')
应该返回如下内容:
{
"script": "console.log('example text');"
}
最佳答案
json.dumps
是转义函数 - 它接受任何值,并使其成为有效的 javascript 文字。
def logIt(self, str):
cmd = "console.log({0});".format(json.dumps(str))
json.dumps({ "script": cmd })
制作:
>>> print logIt('example text')
{ "script": "console.log(\"example text\");" }
>>> print logIt('example "quoted" text')
{ "script": "console.log(\"example \\\"quoted\\\" text\");" }
或者:
import string
import json
import functools
quote_swap = functools.partial(
string.translate, table=string.maketrans('\'"', '"\'')
)
def encode_single_quoted_js_string(s):
return quote_swap(json.dumps(quote_swap(s)))
关于javascript - 在 Python 中转义 JavaScript 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17118714/