2

I use stringify() method in JavaScript to convert a list of objects to a string, but I need to customize the output on the first level ONLY like the following:

[
  /*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}
]

Now there are other parameters in stringfy() method, replacer and space, can't I use them to format my output like the aforementioned format including:

  • tabs
  • spaces
  • comments
3
  • 4
    Last time I checked, comments are not valid in JSON. Commented Feb 25, 2016 at 18:36
  • Also, your array structure starts with { not [ Commented Feb 25, 2016 at 18:38
  • @epascarello I need comments so when I modify an item later, I do it quickly. Commented Feb 25, 2016 at 18:52

1 Answer 1

1

You are not going to get JSON.parse to make that output since it is not valid JSON. But if you want to have something rendered like that, it is a simple loop and string concatenation.

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.