从JSON对象动态创建嵌套列表

密思

我想要实现的是从这样的JSON对象(多级)开始(示例):

[
    {
        "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"
        ]
    }
]

在不知道属性名称或级别的情况下(因为并非对象的所有元素都将具有相同的属性),创建一个基本的嵌套HTML列表,如下所示(其中的键为粗体,值是正常的)。

我已经在SO上尝试了一些解决方案来从JSON创建列表,但是这些解决方案需要属性的名称或知道对象的级别,在我的情况下,该对象将动态生成。

是否可以从未知的JSON对象创建HTML列表?

亚当·阿扎德|

这是我的尝试。欢迎提出建议。

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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章