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

标签 javascript jquery 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 列表,如 this (键是粗体,值是正常的)。

我在 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>

关于javascript - 从 JSON 对象动态创建嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41367907/

相关文章:

javascript - 如何将对象 JSON 转换为 d3.js 数组数据

JavaScript 闭包使用全局设置对象或将其传递给每个函数

jquery - 名称包含两个单词的输入的 Css 选择器?

javascript - 无法在 Javascript 中从数组获取数组

jquery - 旋转 180 度后将图像返回到原始位置

javascript - 在表最后一行(链接)显示菜单并在单击菜单项时显示模态窗口

javascript - 将 JSON 对象写入现有的 .json 文件

php - 将复选框值与输入框值相乘 - Jquery

Javascript 获取 JSON 数组

javascript - 如何在 graphql 中定义不带任何参数的突变或查询?