4

What I want to achieve is, starting from a JSON object (multilevel) like this (example):

[
    {
        "geometry": {
            "location": {
                "lat": 37.3860517,
                "lng": -122.0838511
            },
            "viewport": {
                "northeast": {
                    "lat": 37.4508789,
                    "lng": -122.0446721
                },
                "southwest": {
                    "lat": 37.3567599,
                    "lng": -122.1178619
                }
            }
        },
        "name": "Mountain View",
        "scope": "GOOGLE",
        "data": {
            "customKey1": "customValue1",
            "customKey2": {
                "customSubKey1": {
                    "customSubSubKey1": "keyvalue"
                }
            },
        },
        "types": [
            "locality",
            "political"
        ]
    }
]

Without knowing the name of the properties or the level (because not all the elements of the object will have the same properties) create a basic nested HTML list like this (where the keys are bold and values are normal).

I've tried some solutions here on SO to create a list from JSON, but those solutions need the name of the properties or know the level of the object, and in my case, this object will be generated dynamically.

Is possible to create an HTML list from an unknown JSON object?

Mithc
  • 851
  • 8
  • 23

1 Answers1

3

This is my attempt. Suggestions are welcomed.

function createHTML(json, isArray){
   
   var html = '<ul>';
   for(var key in json){
       if(typeof json[key] == 'object'){
           
           html += '<li>' + (!isArray ? '<strong>'+ key +'</strong>' : '') + '</li>' + createHTML(json[key], (json[key] instanceof Array ? 1 : 0));
       } else {
           html += '<li>'+ json[key] +'</li>';
       }
   }
   return html+'</ul>';

}
  
var jsonData = [
 {
  "geometry": {
   "location": {
    "lat": 37.3860517,
    "lng": -122.0838511
   },
   "viewport": {
    "northeast": {
     "lat": 37.4508789,
     "lng": -122.0446721
    },
    "southwest": {
     "lat": 37.3567599,
     "lng": -122.1178619
    }
   }
  },
  "name": "Mountain View",
  "scope": "GOOGLE",
  "data": {
   "customKey1": "customValue1",
   "customKey2": {
    "customSubKey1": {
     "customSubSubKey1": "keyvalue"
    }
   },
  },
  "types": [
   "locality",
   "political"
  ]
 }
];

document.getElementById('output').innerHTML = createHTML(jsonData, true);
<div id="output"></div>
Adam Azad
  • 11,171
  • 5
  • 29
  • 70
  • This is a nice solution, actually works fine! Just needed to add `html += '
  • '+ key +'
    • ' + json[key] +'
  • ';` on the `else` when is not an object; so it shows the key name as well. Thank you, Adam! – Mithc Dec 28 '16 at 19:20