David David - 1 year ago 70
JSON Question

Dynamic UI from JSON object

I'm trying to find a way to translate a dynamic JSON object into a valid HTML webpage. The idea is to be able to push up what did needs to be displayed from an IoT device into the cloud and have the user be able to input and save the configuration.

The json would look something like this

"loginConfiguration": {
"username": "string",
"password": "string",
"hostname": "string"
"systemConfiguration": {
"numberOfEvents": "int"

And the ideal output would be 3 text boxes with string inputs under a section called loginConfiguration and then another section with 1 integer input. But please note that the json object would differ and should be able to accommodate for that.

I'm open to technology stacks, but it seems to be the most possible with javascript/jQuery. If you have an alternative like Dart that is made for this then please show how this could be accomplished.

Answer Source

I hope you will understand my code , and that i have made it as dynamic as posible , only element you need to know for json is inital object. For example i have used :

var json = 
    "result" : {
        "loginConfiguration" : {
            "username" : "string",
            "password" : "string",
            "hostname" : "string"
        "systemConfiguration" : {
            "numberOfEvents" : "int"

Here is jsFiddle : https://jsfiddle.net/22dx9u7d/

Here is jquery code

var sectionHtml = ""
var controlHtml = ""

var data = JSON.parse(json) 


        //Counts how many sections there are
        var countSections = Object.keys(this).length;
        var i = 0

        //Goes through sections 
         while(i != countSections){   
         var sectionName = Object.keys(this)[i]

         sectionHtml = "<div id='"+ sectionName +"'><h1>Section:"+ sectionName +"</h1>"

            //Goes through sections
            $(data.result[Object.keys(this)[i]]).each(function (index, value) {

                //Count controls inside section
                var countControls = Object.keys(this).length
                var j = 0

                //For each control take data needed
                while(j != countControls){    
                    var controlName = Object.keys(this)[j]
                    var controlType = value[controlName] 

                        //Do your checking  for control type and generate html
                        if(controlType == 'string'){
                            sectionHtml += '<label>'+ controlName +' : </label><input type="text" id="'+ controlName +'" /><br />'
                        }else if(controlType == 'int'){
                            sectionHtml += '<label>'+ controlName +' : </label><input type="number" id="'+ controlName +'" /><br />'



            //Close section html
            sectionHtml += "</div>"
            //Append it to html