Unexpected token ] error during external json file call for cytoscape.js

I am trying to use an external JSON file for creating graph in cytoscape.js. Goal is to get event based changes in graphs (i.e change in input data). For meeting that end, using external JSON files is what came to my mind.

Using the following call for fetching JSON contents:

var treeData;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
      treeData = JSON.parse(this.responseText);

  }
};
xhttp.open("GET", "http://localhost/myfile.json", true);
xhttp.send();

and supplying treeData to elements:

elements: treeData,

(I have tried without parsing the JSON as well).

Following is the structure of JSON file:

{
"nodes": [
  { "data": { "id": "j", "name": "Jerrymmmmmmm", "faveColor": "#6FB1FC", "size": 150} },
  { "data": { "id": "e", "name": "Elainemmmmmmm", "faveColor": "#EDA1ED", "size": 100 } },
  { "data": { "id": "k", "name": "Kramemmmmrmmm",  "faveColor": "#86B342", "size":90 } },
  { "data": { "id": "g", "name": "Georgemmmmmmm",  "faveColor": "#F5A45D", "size":75} },
   ],
"edges": [
  { "data": { "source": "j", "target": "e", "faveColor": "red",  } },
  { "data": { "source": "j", "target": "k", "faveColor": "red",} },
  { "data": { "source": "j", "target": "g", "faveColor": "black",} },
]
  }

Getting the following error: Unexpected token ] in JSON at position 1449 at JSON.parse () at XMLHttpRequest.xhttp.onreadystatechange.

Assistance highly appreciated...thanks

Upvotes: 0

Views: 231

Answers (1)

Matt Spinks
Matt Spinks

Reputation: 6698

You've got some extra commas in there buddy. After "red", after "black", after your last "nodes" object, and after your last "edges" object. Try this:

{
    "nodes": [{
        "data": {
            "id": "j",
            "name": "Jerrymmmmmmm",
            "faveColor": "#6FB1FC",
            "size": 150
        }
    }, {
        "data": {
            "id": "e",
            "name": "Elainemmmmmmm",
            "faveColor": "#EDA1ED",
            "size": 100
        }
    }, {
        "data": {
            "id": "k",
            "name": "Kramemmmmrmmm",
            "faveColor": "#86B342",
            "size": 90
        }
    }, {
        "data": {
            "id": "g",
            "name": "Georgemmmmmmm",
            "faveColor": "#F5A45D",
            "size": 75
        }
    }],
    "edges": [{
        "data": {
            "source": "j",
            "target": "e",
            "faveColor": "red"
        }
    }, {
        "data": {
            "source": "j",
            "target": "k",
            "faveColor": "red"
        }
    }, {
        "data": {
            "source": "j",
            "target": "g",
            "faveColor": "black"
        }
    }]
}

Also, a very useful tool that can help you debug JSON errors is jsonlint: http://jsonlint.com/

Upvotes: 2

Related Questions