最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What would be the best way to pass a list from python to js using bottle? - Stack Overflow

programmeradmin4浏览0评论

I am using Bottle as a web server and need to pass a python list to javascript.

When I am doing just {{myList}}, Bottle escapes single quotes for strings in the list and shows them as ' JS, in turn, isn't very happy with what it gets.

I managed to find a solution, but I don't think it's an optimal one.

var tempList = '{{eval(myList)}}'.replace(/'/g, "'");
var myNewList = eval(tempList);

I wonder, is there a better way to do this?

upd: I moved the solution I found into the 'Answers' section.

I am using Bottle as a web server and need to pass a python list to javascript.

When I am doing just {{myList}}, Bottle escapes single quotes for strings in the list and shows them as ' JS, in turn, isn't very happy with what it gets.

I managed to find a solution, but I don't think it's an optimal one.

var tempList = '{{eval(myList)}}'.replace(/'/g, "'");
var myNewList = eval(tempList);

I wonder, is there a better way to do this?

upd: I moved the solution I found into the 'Answers' section.

Share Improve this question edited Jul 12, 2012 at 20:58 Noemi asked Jul 11, 2012 at 7:13 NoemiNoemi 1331 silver badge8 bronze badges 2
  • 1 If your question is resolved, please either accept the answer that helped you most, or write your own answer which you will be able to accept as well. Please refrain from posting your own answer in an update to the question. – Helgi Commented Jul 11, 2012 at 20:19
  • Also, json in python 3 is the simplejson module, which was integrated into the python standard library some time ago. – Martijn Pieters Commented Jul 12, 2012 at 13:16
Add a ment  | 

3 Answers 3

Reset to default 5

I started using json (json_dumps in Python3, simplejson won't install), but bottle was still escaping single quotes. I found in Bottle manual that you can skip escaping using the exclamation sign and changed my code:

var myNewList = {{!myList}};

Use the json module instead; it outputs valid JavaScript expressions after all.

JSON (JavaScript Object Notation) is a subset of JavaScript syntax (ECMA-262 3rd edition) […]

Quick example:

>>> import json
>>> json.dumps([1, 2, 'foo', 'bar'])
'[1, 2, "foo", "bar"]'

Put that straight into your template. I use this all the time to put valid JavaScript data structures into my generated web pages all the time.

I am not familiar with Bottle, but I do have the same problem when using Django. My solution is dump the Python list to JSON format. Javascript is happy with JSON.

myList = [1, 2, 3, 'string', "&apm;", '"']

Then return simplejson.dumps(myList) to your web pages. In js:

var myList = <dumped-literal-JSON-string>

NOTE: DO NOT surround the dumpped JSON value with quotes.

发布评论

评论列表(0)

  1. 暂无评论