将 Python None 转换为 JavaScript null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9947262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Python None to JavaScript null
提问by Darwin Tech
In a Django view I am generating a data set something like this:
在 Django 视图中,我生成了一个如下所示的数据集:
data = [22, 23, 18, 19, 21, None, 22, 20]
I am passing this data to a JavaScript variable using:
我使用以下方法将此数据传递给 JavaScript 变量:
data_json = simplejson.dumps(data)
For use in a High Charts script.
用于 High Charts 脚本。
Unfortunately JavaScript is stumbling when it encounters the None
value because actually what I need is null
. How can I best replace None
with null
, and where should I handle this - in the Django View or in the JavaScript?
不幸的是,JavaScript 在遇到该None
值时会遇到困难,因为实际上我需要的是null
. 我怎样才能最好地替换None
为null
,我应该在哪里处理这个问题 - 在 Django 视图中还是在 JavaScript 中?
回答by Richard Connamacher
If you're using Python 2.6 or later, you can use the built-in json module:
如果您使用的是 Python 2.6 或更高版本,则可以使用内置的 json 模块:
>>> import json
>>> json.dumps([1, 2, 3, None, 4])
'[1, 2, 3, null, 4]'