Mike
Mike

Reputation: 33

JSON array error

I have the following JSON file (rectangles.json):

{  
   "rectangles":[  
   {  
     "x":0,
     "y":0,
     "width":20,
     "height":10,
     "color":"red"
  },
  {  
     "x":25,
     "y":0,
     "width":20,
     "height":10,
     "color":"red"
  }
]
}

I get the following error: 'Unexpected Token :' on line 2. I can't figure out the issue. Any suggestions? Below is the javascript I have in a local file:

function load(){
 var myData = JSON.parse(rectangles);
 var can = document.getElementById('rectangleCanvas');
 var context = can.getContext('2d');

 for (i=0; i<myData.length; i++){
  context.fillStyle = myData[i].color;
  context.fillRect(myData[i].x, myData[i].y, myData[i].width, myData[i].height);
} 
}

And her is my HTML from another local file:

<!DOCTYPE html>
<html>
<head>
<title>Fetch JSON array Data</title>

<script type="text/javascript" src="myScript.js"></script>
<script type="text/javascript" src="rectangles.json"></script>
</head>
<body>
<canvas id="rectangleCanvas" width="22528" height="20922"></canvas> 
<script>load();</script>
</body>
</html>

Upvotes: 0

Views: 164

Answers (3)

Quentin
Quentin

Reputation: 943561

<script type="text/javascript" src="rectangles.json"></script>

JSON is a data format inspired by JavaScript literal syntax. It is, however, not JavaScript. You can't load it using a <script> element. You need to either:

  1. Write some JavaScript to fetch the JSON using, for example, the XMLHttpRequest object (this is commonly known as Ajax).
  2. Change the JSON to a JavaScript program that creates a global variable you can access
  3. Change the JSON to a JavaScript program that calls a function and passes the data as an argument

Upvotes: 3

TaoPR
TaoPR

Reputation: 6052

Your JSON file looks fine so you might probably try to parse the object which is already a JSON format after you read it from file.

For example if you read it from file and say you store it in a variable rect:

var rect = {  
    "rectangles":[  
    {  
        "x":0,
        "y":0,
        "width":20,
        "height":10,
        "color":"red"
    },
    {  
       "x":25,
       "y":0,
       "width":20,
       "height":10,
       "color":"red"
    }
    ]
}

If you parse that such variable rect again, you'll get an error.

JSON.parse(rect); // throw you an error: Unexpected token

Because the variable is already a JSON format.

Upvotes: 0

Austin Hunt
Austin Hunt

Reputation: 136

You'll get such an error if you're trying to evaluate your JSON file as JavaScript. I copied and pasted your string into the Chrome console and got the same error. But, if I set that JSON string to a variable it works:

    var awesomeRect = {  
       "rectangles":[  
    {  
      "x":0,
      "y":0,
      "width":20,
      "height":10,
      "color":"red"
   },
   {  
      "x":25,
      "y":0,
      "width":20,
      "height":10,
      "color":"red"
   }
 ]
 }

Upvotes: 0

Related Questions