{n:2 , e:1},{fro...">

Getting unexpected token: n when parsing JSON in JavaScript

Grab 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); 

Chrome's JS console says: Uncaught SyntaxError: Unexpected token n

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

+6
source share
2 answers

You need to quote your shortcuts and add parentheses ...

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

Can you try to accept the value, divide it by "," to create an array and use JSON.stringify to generate the correct JSON. From there you can use JSON.parse and have an object

0
source

All Articles