在javascript中从任意复杂的JSON对象生成html

generating html from arbitrarily complex JSON object in javascript

本文关键字:对象 JSON html 复杂 javascript 任意      更新时间:2023-09-26

Javascript/jQuery新手。

我的web服务器正在发送目录树的内容作为JSON对象。对象是根据包含其他子目录的子目录的数量任意嵌套的。它看起来像这样:

{
    "contents": [
        {
            "filename": "myfile",
            "mtime": 123456,
            "size": 2345,
            "content": nil
        },
        {
            "filename": "mydir",
            "mtime": 2345678,
            "size": 3456788,
            "content": [
                {...},
                {...}
            ]
        }
    ]
}

myfile是一个普通文件,所以"content"为空。Mydir是一个目录,它可以是空的,或者包含其他文件或子目录。

我想用javascript解析这个JSON并生成内容的html ul表示。我的问题是:有没有一种简单/推荐的方法来做到这一点?

如果您通过使用jQuery的ajax调用接收JSON文本,jQuery将为您将其反序列化为对象图。如果您以其他方式接收到它,并且它是一个字符串,您可以使用jQuery.parseJSON对它进行反序列化。

但是,你引用的JSON是无效的,特别是这一点:

"content": nil

JSON中没有nil关键字。你会想要修复服务器要么离开钥匙完全关闭,或使用null,或其他东西。有效的JSON是在JSON网站上定义的,您可以使用http://jsonlint.com进行方便的验证(和格式化)。一致使用contentcontents也可能是有用的;当前顶级表项使用contents,下级表项使用content

一旦你有了对象图,它就是一个相当简单的递归函数,循环遍历数组条目,对于可以嵌套内容的条目,再次调用自己来循环遍历。类似这样的内容(live copy):

jQuery(function($) {
  display("Loading the JSON data");
  $.ajax({
    type:     "GET",
    url:      "/path/to/the/data",
    dataType: "JSON",
    success:  function(data) {
      display("Got the data, rendering it.");
      $(document.body).append(renderContents(data.contents));
    },
    error:    function() {
      display("An error occurred.");
    }
  });
  function renderContents(contents) {
    var index, ul;
    // Create a list for these contents
    ul = $("<ul>");
    // Fill it in
    $.each(contents, function(index, entry) {
      var li;
      // Create list item
      li = $("<li>");
      // Set the text
      li.text(entry.filename);
      // Append a sublist of its contents if it has them
      if (entry.content) {
        li.append(renderContents(entry.content));
      }
      // Add this item to our list
      ul.append(li);
    });
    // Return it
    return ul;
  }
  function display(msg) {
    $("<p>").html(msg).appendTo(document.body);
  }
});

使用jQuery。在jQuery ajax函数中,使用json代替dataType,它将自动解析json并返回一个json对象。您可以使用jQuery每个函数循环遍历json数组,并在其中创建包含数据的ui。

$.ajax({url:'ur url',dataType:'json',success:function(result){
var dhtml="<ul>";
$.each(result.contents,function(key,value){
        dhtml+="<li><span>"+value.filename+"</span><span>"+value.mtime+"</span></li>";
  })
dhtml+="</ul>";
$(body).append(dhtml);//Will add the result to ur html body
}
})
每个Api Jquery ajax Api

像这样循环遍历结构最简单的方法通常是编写一个递归("自调用")函数:

// $parent is a jQuery object referring to an element 
// you what to create the tree in.
// data is your (parsed) JSON object.
function displayFileTree($parent, data) {
  if (data["contents"] && data["contents"].length) {
    var contents = data["contents"];
    // create a list element
    $list = $("<ul/>");
    // loop over the "contents"
    for (var i = 0, len = contents.length; i < len; i++) {
       // create list item, set its text and append it to the list
       $item = $("<li/>").text(contents[i].filename).appendTo($list);
       // call this function to create a sublist of the subitems
       displayFileTree($item, contents[i]);
    }
    // add list to parent
    $parent.append($list);
  }
}

(该函数假设JSON是正确的,正如T.J. Crowder的答案所建议的那样,特别是它到处使用"contents"而不是"content"作为键。)

(编辑:我开始写这个之前,克劳德扩展了他的答案与类似的解决方案)