简体   繁体   中英

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM