提问者:小点点

JavaScript const txt更改为新行不起作用[重复]


我正在尝试在Javascript中将txt转换为json fomat,如果我将txt作为以下代码放在1行中,它效果很好:

<html>
<body>

<p id="demo"></p>

<script>
const txt = '{"name":"John", "age":30, "city":"New York","home":"yes"}'
const obj = JSON.parse(txt);
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
</script>

</body>
</html>

然而在我的实际业务中,txt很长,我必须从新行开始,我添加了'/n':

<!DOCTYPE html>
    <html>
    <body>
    
    <p id="demo"></p>
    
    <script>
    const txt = '{"name":"John", "age":30, "city":"New York", + "/n" +
   "home":"yes"}'
    const obj = JSON.parse(txt);
    document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
    </script>
    
    </body>
    </html>

但不管用,有朋友能帮忙吗?


共1个答案

匿名用户

尝试像这样使用转义字符:

const txt = '{"name":"John", "age":30, "city":"New York",\n' +'"home":"yes"}';