从JSON对象动态创建嵌套列表 [英] Create nested list dynamically from JSON object

查看:60
本文介绍了从JSON对象动态创建嵌套列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

在不知道属性名称或级别的情况下(因为并非对象的所有元素都具有相同的属性),创建了一个基本的嵌套HTML列表,例如

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).

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

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.

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

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

推荐答案

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

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>

这篇关于从JSON对象动态创建嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆