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

4

我希望实现的是,从一个类似于以下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列表?

1个回答

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

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>


这是一个不错的解决方案,实际上运行良好!只需要在else中添加html += '<li><strong>'+ key +'</strong><ul><li>' + json[key] +'</li></ul></li>';,当它不是一个对象时,它会显示键名。谢谢,Adam! - Mithc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接