Search code examples
htmljsonnode.jsuser-interfacelighthouse

Creating a UI/writing HTML from a JSON file


I have a really long, unwieldy, unformatted JSON file generated by Lighthouse (a tool that conducts page load time analysis- so this file has the results of the tests). In order to make it formatted to be readable by people, I need to apparently create a UI around this file. My problem is that I'm not sure how to begin working on it.

I've read about something like creating HTML from JSON objects, I think I'd like to try that to just display all the information from the tests in the browser right now... But where would I write that? I have one Node.js file right now, which is running the tests and using JSON.stringify() to stick the JSON'd results into a file. Can I generate the HTML right after I create the JSON? (And the main question- how would I create HTML from a JSON file?)

I'm just starting out with Node and JSON, any tips are highly appreciated.


Solution

  • Yes, you can create HTML from a JSON file.

    Here's a simple example done with jQuery, first creating an array of all of the elements, and then using .join("") to parse them. Once parse, they can simply be appended anywhere in the DOM:

    var json_file = {
      "one": "Hi there",
      "two": "Another item",
      "three": "Third item"
    }
    
    var items = [];
    
    $.each(json_file, function(key, val) {
      items.push("<li id='" + key + "'>" + val + "</li>");
    });
    
    $("<ul/>", {
      "class": "json-list",
      html: items.join("")
    }).appendTo("body");
    
    // Sample extension showcasing manipulation of inserted HTML
    $(".json-list #two").css('color', 'red');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    Obviously, the more complicated your JSON (and desired HTML structure), the more complicated the method of parsing the JSON is going to be.

    A templating engine would make your job significantly easier, and there and hunderds of these. Some of the more popular ones are:

    Hope this helps! :)