sheetjs icon indicating copy to clipboard operation
sheetjs copied to clipboard

Parsing hierarchical data from spreadsheet

Open nj-sketch opened this issue 9 years ago • 2 comments

I have a spreadsheet with hierarchical data .Parsing it to json format works for simple excel format. But I want to parse the data as well like

[
  {
    "ItemNo": "1.1.1",
    "#": "1",
    "WorkType": "Construction",
    "Work": "test",
    "Barrier": {
      "1": "testA",
      "2": "testB"
    }
  },
  {
    "ItemNo": "1.1.2",
    "#": "1",
    "WorkType": "Construction2",
    "Work": "test",
    "Barrier": {
      "1": "testA",
      "2": "testB"
    }
  }
]

How can I do it? Any small hint would be also great at this point.

nj-sketch avatar Nov 09 '17 10:11 nj-sketch

If you set the option {header:1}, the result will be a simple array of arrays that you can manually process. The merge ranges are available as an array !merges:

/* assuming `ws` is your worksheet */
var aoa = XLSX.utils.sheet_to_json(ws, {header:1, raw:true})

ws['!merges'].forEach(function(m) {
	/* first row with merged columns */
	if(m.s.r == 0 && m.e.r == 0) for(var i = m.s.c+1; i <= m.e.c; ++i) aoa[0][i] = aoa[0][m.s.c];
	/* first two rows of a given column */
	if(m.s.r == 0 && m.e.r == 1 && m.s.c == m.e.c) { aoa[1][m.s.c] = aoa[0][m.s.c]; aoa[0][m.s.c] = ""; }
});

var out = [];
aoa.slice(2).forEach(function(row) {
	var data = {};
	row.forEach(function(r, i) {
		if(aoa[0][i]) {
			data[aoa[0][i]] = data[aoa[0][i]] || {};
			data[aoa[0][i]][aoa[1][i]] = r;
		} else data[aoa[1][i]] = r;
	});
	out.push(data);
});

Example:

[ { a: 'x', b: 'z', c: { a: 3, b: 4 }, d: { '1': 5, '2': 6 } },
  { a: 'y', b: 'w', c: { a: 4, b: 5 }, d: { '1': 6, '2': 7 } } ]

SheetJSDev avatar Nov 09 '17 16:11 SheetJSDev

Hey can you help me with slight modification here! Here is the screenshot of the data https://prnt.sc/h8j9lo

Here is the required JSON format

[
  {
    "A": "1",
    "B": "2",
    "E": [
      {
        "a": "3",
        "b": "4",
        "c": "5"
      },
      {
        "a": "5",
        "b": "6",
        "c": "7"
      },
      {
        "a": "8",
        "b": "9",
        "c": "10"
      }
    ],
    "F": {
      "a": "5",
      "b": "2",
      "c": "6"
    },
    "G": "10",
    "H": "11",
    "I": {
      "a": "5",
      "b": "2",
      "c": "6"
    },
    "J": "12"
  }
]

Above code works only one value. But it does not work for my case. How can I tweak it?

nj-sketch avatar Nov 10 '17 05:11 nj-sketch