I have a Python script that builds some JavaScript to send down to the browser in a JSON envelope. I'd like to escape the JavaScript strings and delimit them with single quotes. I can't use json.dumps
because it uses double quotes as delimiters like the JSON spec requires.
Is there a JavaScript String escape method in Python?
Example
def logIt(self, str):
#todo: need to escape str here
cmd = "console.log('%(text)s');" % { 'text': str}
json.dumps({ "script": cmd })
So logIt('example text')
should return something like this:
{
"script": "console.log('example text');"
}
To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert.
Using the Escape Character ( \ ) We can use the backslash ( \ ) escape character to prevent JavaScript from interpreting a quote as the end of the string. The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.
The only characters you normally need to worry about in a javascript string are double-quote (if you're quoting the string with a double-quote), single-quote (if you're quoting the string with a single-quote), backslash, carriage-return (\r), or linefeed (\n).
In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return.
json.dumps
is that escaping function - it takes any value, and makes it a valid javascript literal.
def logIt(self, str):
cmd = "console.log({0});".format(json.dumps(str))
json.dumps({ "script": cmd })
Producing:
>>> print logIt('example text')
{ "script": "console.log(\"example text\");" }
>>> print logIt('example "quoted" text')
{ "script": "console.log(\"example \\\"quoted\\\" text\");" }
Or:
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With