sqlcmd parser

Take the command line output from sqlcmd.exe and parse it into an array of JSON objects.

by Kyle Falconer

HTML

<div id="disp">

</div>

JavaScript

var input = 'biCalSeqID           Plaza_Name Interval_Starting       Pricing_Module Message_Module                             User                                               Algorithm_Mode                                    \n-------------------- ---------- ----------------------- -------------- ------------------------------------------ -------------------------------------------------- --------------------------------------------------\n              356963 CLW        2016-05-06 17:40:00.000 1.00           HOV 2+ NO TOLL                             SYSTEM                                             EL Speed                                          \n              356963 FSE        2016-05-06 17:40:00.000 2.20           HOV 2+ NO TOLL                             SYSTEM                                             EL Speed                                          ';

function parseSqlCmd(response) {
  var lines = response.split('\n');
  var labels = lines[0].replace(/\s\s+/g, ' ').split(' ');
  // console.log('labels : ', labels);
  var split = lines[1].split(' ');
  var counts = [];
  for (var i = 0; i < split.length; i++) {
    counts.push(split[i].length);
  }
  var res = [];
  var label_index = 0;
  for (var i = 2; i < lines.length; i++) {
    var line = lines[i];
    var obj = {};

    var line_index = 0;
    // console.log(line, line.length);
    for (var j = 0; j < counts.length; j++) {
      var end = line_index + counts[j];
      var sliced = line.slice(line_index, end - 1);
      obj[labels[label_index]] = sliced.trim();
      // console.log(labels[label_index]+' : '+obj[labels[label_index]]);
      line_index += counts[j] + 1;
      label_index++;
    }
    res.push(obj);
    label_index = 0
  }
  res.pop();	// the last element is empty
  return res;
}

(function() {
  $('#disp').append(JSON.stringify(parseSqlCmd(input)) + '<br/><br/>');
})();