在Python中转义JavaScript字符串

2024-06-07 13:35:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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');"
}

Tags: 字符串text脚本cmdlogjsonexamplescript
1条回答
网友
1楼 · 发布于 2024-06-07 13:35:01

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)))

相关问题 更多 >

    热门问题