Mike
Mike

Reputation: 33

Eclipse JSON format

I'm using a JSON file to store an array of rectangle attributes. Then, in a separate javascript file, I parse the JSON and draw the rectangles on a canvas. For some reason, Eclipse likes this JSON format and the Chrome debugger accepts it:

rectangles = '[{"x" : 0, "y" : 0, "width" : 20, "height" : 10, "color" : "red"}, {"x" : 25, "y" : 0, "width" : 20, "height" : 10, "color" : "blue"}, {"x" : 0, "y" : 15, "width" : 20, "height" : 10, "color" : "blue"}, {"x" : 25, "y" : 15, "width" : 20, "height" : 10, "color" : "red"}]';

but when I clean it up and try to format it, Eclipse no longer draws the rectangles with this format:

rectangles='[
  {
    "x": 0,
    "y": 0,
    "width": 20,
    "height": 10,
    "color": "red"
  },
  {
    "x": 25,
    "y": 0,
    "width": 20,
    "height": 10,
    "color": "blue"
  },
  {
    "x": 0,
    "y": 15,
    "width": 20,
    "height": 10,
    "color": "blue"
  },
  {
    "x": 25,
    "y": 15,
    "width": 20,
    "height": 10,
    "color": "red"
  }
]';

Is there a reason why it only draws the rectangles with the former format? For reference, here is my javascript:

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

Upvotes: 0

Views: 1292

Answers (2)

Luca Fagioli
Luca Fagioli

Reputation: 13359

For your specific error check Tony's answer.

By the way, from your snippet appears strange that you declare it as a String and then parse it later, though.

Why not this?

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

function load(){

    var can = document.getElementById('rectangleCanvas');
    var context = can.getContext('2d');

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

Upvotes: 0

Tony
Tony

Reputation: 2483

If you want the string to extend across lines you have to end the string and add:

var myLongString = 'This' +
    'is' +
    'my long string.';

I plopped your "cleaned-up" rectangles into a jsfiddle and you can see the console log the error:

SyntaxError: unterminated string literal

Upvotes: 2

Related Questions