简体   繁体   English

获得意外的令牌:n在JavaScript中解析JSON时

[英]Getting unexpected token: n when parsing JSON in JavaScript

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控制台说:Uncaught SyntaxError: Unexpected token n

can't find out where is that token n can be and what's wrong with my code? 无法找出令牌n可以在哪里以及我的代码有什么问题? any ideas? 有任何想法吗?

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
    }
]

Can you try to take the value, split it by ',' to create an array and use JSON.stringify to generate a correct JSON. 您可以尝试获取值,将其拆分为“,”以创建数组并使用JSON.stringify生成正确的JSON。 From there you can use JSON.parse and have an object 从那里你可以使用JSON.parse并拥有一个对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM