如何使用JavaScript的stringify()方法在第一级自定义JSON输出?

时间:2016-02-25 18:30:57

标签: javascript arrays json

我在JavaScript中使用stringify()方法将对象列表转换为字符串,但我需要在第一级 ONLY 上自定义输出,如下所示:

[
  /*T01*/ {"startX":55,"endX":109,"sartY":0,"endY":249},
  /*T02*/ {"startX":110,"endX":164,"sartY":0,"endY":249},
  /*T03*/ {"startX":165,"endX":219,"sartY":0,"endY":249},
  /*T04*/ {"startX":220,"endX":274,"sartY":0,"endY":249},
  /*T05*/ {"startX":275,"endX":329,"sartY":0,"endY":249},
  /*T06*/ {"startX":330,"endX":384,"sartY":0,"endY":249},
  /*T07*/ {"startX":385,"endX":439,"sartY":0,"endY":249},
  /*T08*/ {"startX":440,"endX":494,"sartY":0,"endY":249},
  /*T09*/ {"startX":495,"endX":549,"sartY":0,"endY":249},
  /*T10*/ {"startX":550,"endX":604,"sartY":0,"endY":249}
]

现在在stringfy()方法,替换器和空间中还有其他参数,我不能用它们来格式化我的输出,如上述格式包括:

  • 突片
  • 空间
  • 评论

1 个答案:

答案 0 :(得分:1)

你不会让JSON.parse来输出,因为它不是有效的JSON。但是如果你想要有类似的东西,它就是一个简单的循环和字符串连接。



var details = [
    {"startX":55,"endX":109,"sartY":0,"endY":249},
    {"startX":110,"endX":164,"sartY":0,"endY":249},
    {"startX":165,"endX":219,"sartY":0,"endY":249},
    {"startX":220,"endX":274,"sartY":0,"endY":249},
    {"startX":275,"endX":329,"sartY":0,"endY":249},
    {"startX":330,"endX":384,"sartY":0,"endY":249},
    {"startX":385,"endX":439,"sartY":0,"endY":249},
    {"startX":440,"endX":494,"sartY":0,"endY":249},
    {"startX":495,"endX":549,"sartY":0,"endY":249},
    {"startX":550,"endX":604,"sartY":0,"endY":249}
];

var out = "[\n" + details.map(function(val, i) {
  var id = "\t/*T" + ("0" + (i + 1)).substr(-2) + "*/\t";
  return id + JSON.stringify(val);
}).join(",\n") + "\n]";
console.log(out);