[英]I am getting “SyntaxError: Unexpected token ' in JSON at position 1” when using JSON.parse
I'm having trouble accessing the list param = ['foo','bar']
on myView.js
. 我在访问
myView.js
上的列表param = ['foo','bar']
时myView.js
。
the JS code is treating param
as if it were a string, but when I try JSON.parse(param)
I get the error shown below. JS代码将
param
当作字符串对待,但是当我尝试JSON.parse(param)
,出现如下所示的错误。
What am I missing here? 我在这里想念什么?
<script>
window.obj = {};
obj.param = "{{ param | safe }}";
</script>
def myView(req):
context = {'param':['foo','bar']}
return render(req, 'myView.html', context)
$(document).ready(function() {
console.log(window.obj.param); //prints ['foo','bar']
console.log(window.obj.param[0]); //prints [
console.log(JSON.parse(window.obj.param)); // Uncaught SyntaxError: Unexpected token ' in JSON at position 1
//what I need to happen
console.log(param[0]); // prints 'foo'
});
json format allows only double quotes ( token ' in JSON at position 1
), sting with single quotes is not a valid json format, so if you try to parse it, you will get an error, as demonstrated here json格式仅允许使用双引号(
token ' in JSON at position 1
),单引号的字符串不是有效的json格式,因此,如果您尝试解析它,则会收到错误,如此处所示
function safeParse(param){ try { console.log(JSON.parse(param)) } catch (e) { console.log("there was an issue with parsing your string") } } safeParse("['foo','bar']"); safeParse('["foo","bar"]');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.