Json - stringify so that arrays are on one line

Chris Glasier picture Chris Glasier · Aug 4, 2011 · Viewed 16.3k times · Source

Is it possible to stringify a JSON object to look like this, with arrays in one line - not indented

{
    "Repeat": {
        "Name": [["Top_level","All"],[[1,1]]],
        "Link": [["Top_level"],[[1,1]]]
    },
    "Delete": ["Confirm","Cancel"],
    "Move": ["Up","Down"],
    "Number": ["Ascending","Descending"]
}

Answer

ericbowden picture ericbowden · Aug 26, 2013

Try this:

var obj = {"Repeat": {"Name":[["Top_level","All"],[[1,1]]],"Link": [["Top_level"],[[1,1]]]},"Delete": ["Confirm","Cancel"],"Move": ["Up","Down"],"Number": ["Ascending","Descending"]};

JSON.stringify(obj,function(k,v){
   if(v instanceof Array)
      return JSON.stringify(v);
   return v;
},2);

Result:

"{
  "Repeat": {
    "Name": "[[\"Top_level\",\"All\"],[[1,1]]]",
    "Link": "[[\"Top_level\"],[[1,1]]]"
  },
  "Delete": "[\"Confirm\",\"Cancel\"]",
  "Move": "[\"Up\",\"Down\"]",
  "Number": "[\"Ascending\",\"Descending\"]"
}"