JSON.parse()函数无法在javascript中运行

时间:2021-12-22 01:47:59

I have a list that i am trying to parse to a json object, ["Harry ", "Potter ", "Name ", "Batman"]. I am using Django templates for this. I have parsed the list using simplejson.dumps(). I am trying to parse this in my javascript code.It is working fine until the line document.getElementById("demo").innerHTML = x; in my code, it is printing ["Harry ", "Potter ", "Name ", "Batman"] correctly.but JSON.parse() is not working.The lines written after calling parse are not working. Can anyone tell me the problem with this code?

我有一个列表,我试图解析一个json对象,[“哈利”,“波特”,“名字”,“蝙蝠侠”]。我正在使用Django模板。我使用simplejson.dumps()解析了列表。我试图在我的javascript代码中解析它。它正常工作,直到行document.getElementById(“demo”)。innerHTML = x;在我的代码中,它正确地打印[“Harry”,“Potter”,“Name”,“Batman”]。但JSON.parse()不起作用。调用parse后写的行不起作用。谁能告诉我这段代码的问题?

{%extends 'base.html'%}

{%block content%}

<p id="demo">hai {{y}} im</p>

<script>

var x = (("{{y}}").replace(/&(l|g|quo)t;/g, function(a,b){
               return {
                   l   : '<',
                   g   : '>',
                   quo : '"'
               }[b];
           }));
x = x.replace(/u'/g, '\'');
x = x.replace(/'/g, '\"');
document.getElementById("demo").innerHTML = x;
p = JSON.parse( x );
document.getElementById("demo").innerHTML="Aray";
</script>
{%endblock%}

Thanks

谢谢

1 个解决方案

#1


0  

Maybe you need to stringify it before you parse it. Look at the example below:

也许你需要在解析之前对其进行字符串化。看下面的例子:

var arr = ["a", "b", "c"];
var str = JSON.stringify(arr);
document.write(str);
document.write ("<br/>");

var newArr = JSON.parse(str);

#1


0  

Maybe you need to stringify it before you parse it. Look at the example below:

也许你需要在解析之前对其进行字符串化。看下面的例子:

var arr = ["a", "b", "c"];
var str = JSON.stringify(arr);
document.write(str);
document.write ("<br/>");

var newArr = JSON.parse(str);