lwiii
lwiii

Reputation: 4979

Getting unexpected token: n when parsing JSON in JavaScript

Grabbing innerHTMl of this div

<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

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

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

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

Upvotes: 9

Views: 33264

Answers (2)

drioemgaoin
drioemgaoin

Reputation: 26

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

Upvotes: 0

Kevin Garman
Kevin Garman

Reputation: 395

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

Upvotes: 20

Related Questions