Brian Crist Brian Crist - 1 year ago 109
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, 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": [
"data": [

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

Answer Source

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

    //now build your data item[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];[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));

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download