Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 705
lwiii Avatar asked Feb 17 '13 22:02

lwiii


People also ask

How do you handle JSON parsing error?

The most common way to handle JSON parse error is using try-catch block. If the JSON string is valid, it will return a JavaScript object. If the JSON string is invalid, it will throw a SyntaxError.

What is JSON parse error unrecognized token?

This most probably means the response you are getting from the webserver is not a JSON object, instead, it is an HTML document.

What does this mean SyntaxError unexpected token in JSON at position 0?

Re: Unexpected token in JSON at position 0 This usually means that an error has been returned and that's not valid JSON. Check the browser developer tools console and network tabs. Turn on Debugging and (after reproducing the error) check the web server error logs.


1 Answers

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
    }
]
like image 132
Kevin Garman Avatar answered Oct 19 '22 09:10

Kevin Garman