Pwnna
Pwnna

Reputation: 9528

escaping data passed by python to Javascript (JSON)

I have some data that I need to pass to JavaScript on a page. I'm using jinja2 to generate my page and here's how this is going:

In python:

some_json_data = json.dumps(some_data)

In jinja2:

JSON.parse('{% autoescape off %}{{ some_json_data }}{% endautoescape %}')

However, sometimes, some_json_data could contain strings with \n as well as '. Is there a library/some known function that I could use to escape these?

I know I could write this function with no problem, but I was wondering if there's already a library or something that does this. I've been looking around and haven't found anything.

Side note: My application is built on using Flask

Upvotes: 0

Views: 140

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121346

You don't need to use JSON.parse; the output is already valid JavaScript. You then don't need to put quotes around the JSON value either.

Generally, my JavaScript looks like:

<script language="javascript" type="text/javascript">
    var serverJSValue = {% autoescape off %}{{ some_json_data }}{% endautoescape %};
</script>

Upvotes: 1

Related Questions