Brian Crist Brian Crist - 1 month ago 22
Javascript Question

How to parse JSON to JSON in javascript?

That so crazy, but I'm trying to convert a JSON to a JSON for any reason.I have json and i checked json at http://jsonlint.com, it's ok.

{"d": "[{\"ID\":\"VN00000123\",\"NAME\":\"JOHN GREEN\",\"GENDER\":\"Male\",\"BIRTHDAY\":\"15-10-1987\"},{\"ID\":\"VN00000456\",\"NAME\":\"MERRY BLUE\",\"GENDER\":\"Female\",\"BIRTHDAY\":\"03-12-1983\"},{\"ID\":\"VN00000789\",\"NAME\":\"BLACK BROWN\",\"GENDER\":\"Male\",\"BIRTHDAY\":\"09-07-1990\"}]"}


Now, what I need convert it like this at the following

{
"columns": [
["ID"],
["NAME"],
["GENDER"],
["BIRTHDAY"]
],
"data": [
[
"VN00000123",
"JOHN GREEN",
"Male",
"15-10-1987"
],
[
"VN00000456",
"MERRY BLUE",
"Female",
"03-12-1983"
],
[
"VN00000789",
"BLACK BROWN",
"Male",
"09-07-1990"
]
]
}


Somebody've ideas for this, share with me (using javascript or jquery). Thank you so much.

Answer

This algorithm is pretty straightforward--something like the following should work:

function parse(a) {
  //create object to return
  var ret = {
    columns: [],
    data: []
  };

  //iterate the source array
  a.forEach(function(item, i) {
    if (i === 0) {
      //first time through, build the columns
      for (var key in item) {
        ret.columns.push(key);
      }
    }

    //now build your data item
    ret.data[i] = [];

    //use the column array to guarantee that the order of the fields in the source string doesn't matter
    for (var j = 0; j < ret.columns.length; j++) {
      var key = ret.columns[j];
      ret.data[i].push(item[key]);
    }
  });
  return ret;
}

var j = {
  "d": "[{\"ID\":\"VN00000123\",\"NAME\":\"JOHN GREEN\",\"GENDER\":\"Male\",\"BIRTHDAY\":\"15-10-1987\"},{\"NAME\":\"MERRY BLUE\",\"BIRTHDAY\":\"03-12-1983\",\"ID\":\"VN00000456\",\"GENDER\":\"Female\"},{\"GENDER\":\"Male\",\"ID\":\"VN00000789\",\"NAME\":\"BLACK BROWN\",\"BIRTHDAY\":\"09-07-1990\"}]"
};

//j is an object with one property (d) that is a JSON string that needs parsing
var o = parse(JSON.parse(j.d));
console.log(o);