在 JavaScript 中解析 JSON 时获得意外标记:n

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14926640/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 18:21:32  来源:igfitidea点击:

Getting unexpected token: n when parsing JSON in JavaScript

javascriptjson

提问by lwiii

Grabbing innerHTMl of this div

抓取这个div的innerHTMl

<div style="display:none;" id="graphdata">{n:2 , e:1},{from:1 , to:2},{from:2, to:3},{from:3, to:4}</div>

then parsing it with this JS code

然后用这个JS代码解析它

jdiv=document.getElementById('graphdata').innerHTML;
edges=JSON.parse(jdiv);

JS console in Chrome says: Uncaught SyntaxError: Unexpected token n

Chrome 中的 JS 控制台说:未捕获的语法错误: Unexpected token n

can't find out where is that token n can be and what's wrong with my code? any ideas?

无法找出令牌 n 可以在哪里以及我的代码有什么问题?有任何想法吗?

回答by Kevin Garman

You need to quote your labels and add brackets...

您需要引用标签并添加括号...

[
    {
        "n": 2,
        "e": 1
    },
    {
        "from": 1,
        "to": 2
    },
    {
        "from": 2,
        "to": 3
    },
    {
        "from": 3,
        "to": 4
    }
]

回答by drioemgaoin

Can you try to take the value, split it by ',' to create an array and use JSON.stringify to generate a correct JSON. From there you can use JSON.parse and have an object

你能不能尝试取值,用 ',' 分割它来创建一个数组并使用 JSON.stringify 来生成一个正确的 JSON。从那里你可以使用 JSON.parse 并拥有一个对象