Eclipse JSON format

Eclipse JSON format

本文关键字:format JSON Eclipse      更新时间:2023-09-26

我使用JSON文件来存储矩形属性数组。然后,在一个单独的javascript文件中,我解析JSON并在画布上绘制矩形。由于某些原因,Eclipse喜欢这种JSON格式,并且Chrome调试器接受它:

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"}]';

,但是当我清理它并尝试格式化它时,Eclipse不再用这种格式绘制矩形:

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"
  }
]';

是否有一个原因,为什么它只绘制矩形与前格式?作为参考,这是我的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);
  }
}

如果您希望字符串跨行扩展,则必须结束字符串并添加:

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

我将"已清理"的rectangles放入jsfiddle中,您可以看到控制台记录的错误:

SyntaxError: unterminated string literal

对于您的具体错误,请检查Tony的答案。

顺便说一下,从您的代码片段中,您将其声明为String,然后稍后再解析它,这看起来很奇怪。

为什么不呢?

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