Javascript Effectively Build Table From JSON and Add It to DOM

后端 未结 5 1220
感动是毒
感动是毒 2020-12-09 05:59

I have a JSON array coming in from the server with an array of 200 objects each containing another 10 objects that I want to display in a table format. At first I was creati

5条回答
  •  清歌不尽
    2020-12-09 06:28

    If you have a validating string of JSON from the server and the structure is reliably an array of arrays of strings, the below will allow you to avoid a JSON parse, and instead replace the HTML generation with a constant series of regular expression operations which tend to be implemented in native code that uses native buffers. This should avoid one parse altogether and replace any buffer copies that cost O(n**2) with k, O(n) buffer copies for a 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(/")
    html = html.replace(/]\s*$/g, "")
    // Introduce row boundaries.
    html = html.replace(/\],?/g, "")
    html = html.replace(/\[/g, "")
    // Introduce cell boundaries.
    html = html.replace(/,/g, "")
    
    // 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);
    

提交回复
热议问题