8

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');"
}
5
  • It seems to me that your code returns exactly what you need… Commented Jun 14, 2013 at 23:34
  • 1
    Not for logIt('Uh oh\'') Commented Jun 14, 2013 at 23:34
  • Why do you care about single vs double quotes? Commented Jun 14, 2013 at 23:35
  • Oh, yeah, I see now. This probably should've been mentioned in the questions… Commented Jun 14, 2013 at 23:37
  • I care because a single quote is 1/4 the size of \\\" and I have a lot to send over the wire. Commented Jun 15, 2013 at 4:00

1 Answer 1

12

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)))
Sign up to request clarification or add additional context in comments.

6 Comments

Yeah, I know about json.dumps, but I want to avoid having \\\" for quotes that can be just '
@LanceFisher: But you can't avoid the \\\" here - the original text contained a ". I assume you're referring to the \"?
You're right, in this example it is the \". json.dumps that puts double quotes around it. Basically, I want a json.dumps() that outputs single quotes instead.
json.dumps would be a security risk. (If the script is inside a <script> tag in html), json.dumps('</script>') returns "</script>". See owasp.org/index.php/… for right escaping
@TahaJahangir: That's only an issue if you use it in a context like print '<script>var myData = ' + json.dumps(...) + '; ... </script>'. If the json isn't directly injected into the page, as the OP is describing in this quesion, it's fine.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.