If you have a JSON test string from the server, and the structure reliably represents an array of string arrays, then below you can avoid JSON analysis and instead replace HTML generation with a constant sequence of regular expressions which, as a rule, are implemented in native code that uses its own buffers. This should completely eliminate one parsing and replace any buffer copies that cost O (n ** 2) with k, O (n) buffer copies for constant k.
var jsonContent = ' [ [ "foo", "bar", "[baz\\"boo\\n]" ], ["1","2" , "3"] ] '; var repls = { // Equivalent inside a JSON string. ',': "\\u002b", '[': "\\u005b", ']': "\\u005d" }; var inStr = false; // True if the char matched below is in a string. // Make sure that all '[', ']', and ',' chars in JSON content are // actual JSON punctuation by re-encoding those that appear in strings. jsonContent = jsonContent.replace(/[\",\[\]]|\\./g, function (m) { if (m.length === 1) { if (m === '"') { inStr = !inStr; } else if (inStr) { return repls[m]; } } return m; }); // Prevent XSS. jsonContent = jsonContent.replace(/&/g, "&") .replace(/</g, "<"); // Assumes that the JSON generator does not encode '<' as '\u003c'. // Remove all string delimiters and space outside of strings. var html = jsonContent .replace(/\"\s*([,\]])\s*\"?|\s*([\[,])\s*\"/g, "$1$2"); // Introduce the table header and footer. html = html.replace(/^\s*\[/g, "<table>") html = html.replace(/]\s*$/g, "</table>") // Introduce row boundaries. html = html.replace(/\],?/g, "</tr>") html = html.replace(/\[/g, "<tr><td>") // Introduce cell boundaries. html = html.replace(/,/g, "<td>") // Decode escape sequences. var jsEscs = { '\\n': '\n', '\\f': '\f', '\\r': '\r', '\\t': '\t', '\\v': '\x0c', '\\b': '\b' }; html = html.replace(/\\(?:[^u]|u[0-9A-Fa-f]{4})/g, function (m) { if (m.length == 2) { // Second branch handles '\\"' -> '"' return jsEscs[m] || m.substring(1); } return String.fromCharCode(parseInt(m.substring(2), 16)); }); // Copy and paste with the below to see the literal content and the table. var pre = document.createElement('pre'); pre.appendChild(document.createTextNode(html)); document.body.appendChild(pre); var div = document.createElement('div'); div.innerHTML = html; document.body.appendChild(div);
Mike samuel
source share