Skip to content Skip to sidebar Skip to footer

Create Nested List Dynamically From JSON Object

What I want to achieve is, starting from a JSON object (multilevel) like this (example): [ { 'geometry': { 'location': { 'lat': 37.3860517,

Solution 1:

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>

Post a Comment for "Create Nested List Dynamically From JSON Object"