1

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.

Brian Crist
  • 806
  • 3
  • 16
  • 42

3 Answers3

3

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);
Dave
  • 10,748
  • 3
  • 43
  • 54
  • Dear @dave , first thank you so much about this algorithm, but i see results still further key fields `ID,NAME,GENDER,BIRTHDAY` – Brian Crist Oct 27 '16 at 03:44
  • @ochi oh I misread the desired output. I edited the answer now so that data is a 2D array. – Dave Oct 27 '16 at 03:53
2

You can try this example using jQuery:

https://jsfiddle.net/de02fpha/

var dump = {"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\"}]"};

var parse = function(json) {
  var columns = [];
  var data = [];
  $.each(json, function(index, row) {
    var element = [];
    for (var key in row) {
      if (columns.indexOf(key) == -1) columns.push(key);
      element.push(row[key]);
    }
    data.push(element);
  });

  return {columns: columns, data: data};
};


var json = $.parseJSON(dump.d);
console.log(parse(json));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
blurfus
  • 13,485
  • 8
  • 55
  • 61
Thanh TRAN CONG
  • 293
  • 1
  • 7
  • 1
    The problem with this answer is it is dependent on the order of the fields in the JSON string. For example, if in the second item has the Name is the first position and the ID is the second position, those fields would not always display consistently in the same order as the column array. – Dave Oct 27 '16 at 03:59
0

In javascript, the built in JSON class provides the two tools you need to format your JSON, no need for jquery:

JSON.parse() will handle parsing the text, and JSON.stringify can handle taking our parsed JSON and turning into a nice pretty string.

Let's slap them together.

Start with parsing and storing the JSON:

var parsedData = JSON.parse(dataToFormat);

Now to print our parsed data, we need to learn a little bit about the stringify function, specifically its space argument. Per MDN:

JSON.stringify(value[, replacer[, space]])

The space argument may be used to control spacing in the final string. If it is a number, successive levels in the stringification will each be indented by this many space characters (up to 10). If it is a string, successive levels will be indented by this string (or the first ten characters of it).

JSON.stringify({ uno: 1, dos: 2 }, null, '\t');
// returns the string:
// '{
//     "uno": 1,
//     "dos": 2
// }'

Note that the above code sample uses the tab character, but as described in the doc you can simply insert a number and it will use that number of spaces instead.

Alright let's print

var prettyData = JSON.stringify(parsedData, null, '\t');

prettyData should now contain a neatly formatted and indented string.

You can throw this into one line if you'd like:

var prettyData = JSON.stringify(JSON.parse(dataToFormat),null,'\t');

Now, if you wanted to add a key or something to the very top of the JSON object, you could simply define some kind of key object and attach it to the object you pass in to JSON.stringify. JSON.parse gives you a standard object, so modify it like you would any other.

Chuck Dries
  • 1,630
  • 13
  • 19