3

我正在尝试使用 jquery getJson 解析 json 文件。我在第一层循环没有问题,但我也需要为 li 分配一个嵌套数组。

我的 JSON 代码

{"Controls":[
{
    "Object":"Button",
    "ButtonAttr": [{"x": "1","y": "2","width": "3","height": "4"}]
},
{
    "Object":"Image",
    "ButtonAttr": [{"x": "5","y": "6","width": "7","height": "8"}]
},
{
    "Object":"TextField",
    "ButtonAttr": [{"x": "9","y": "10","width": "11","height": "12"}]
}
]}

我的 JS/JQUERY 代码可以毫无问题地引入 JSON 的第一层并将其附加到 li。我需要弄清楚如何获得“ButtonAttr”层

 //Get JSON File which contains all Controls
$.getJSON('controls.json', function(data) {
    //Build Objects List
    var objectList="<ul>";
    for (var i in data.Controls) {
        objectList+="<li>" + data.Controls[i].Object +"</li>";
    }

    objectList+="</ul>";
    $('#options').append(objectList);

    //Add new Code Object based on #Options LI Index
    $(document).on('click','#options li', function() {
        var index = $('#options li').index(this);
        $('#code').append('<li>' + data.Controls[index].Object + '</li>');
        //Shows Selected LI Index
        $('#optionsIndex').text("That was div index #" + index);
    });

});

我一辈子都无法让它遍历第二个数组并列出 x、y、width 和 height 字段。

这是我想要的输出

<ul>
<li>Button</li>
<ul>
    <li>x:1</li>
    <li>y:2</li>
    <li>width:3</li>
    <li>height:4</li>
</ul>
<li>Image</li>
<ul>
    <li>x:5</li>
    <li>y:6</li>
    <li>width:7</li>
    <li>height:8</li>
</ul>
<li>TextField</li>
<ul>
    <li>x:9</li>
    <li>y:10</li>
    <li>width:11</li>
    <li>height:12</li>
</ul>
</ul>

任何帮助将不胜感激

4

4 回答 4

1

我在另一个问题中解决了这个问题。

如何处理 json 中的逗号分隔对象?([对象对象],[对象对象])

您需要一个递归函数,它启动一个 <ul> 并为列表中的每个项目添加 <li>。它还测试项目,如果它们本身是列表,它会以该数据作为参数调用自身。每次从函数内部调用该函数时,您都会在 <ul> 中得到一个 <ul>。

function buildULfromOBJ(obj){
  var fragments = [];

  //declare recursion function
  function recurse(item){
    fragments.push('<ul>'); // start a new <ul>

    $.each(item, function(key, val) {  // iterate through items.

      if((val != null) && (typeof val == 'object') &&   // catch nested objects
               ((val == '[object Object]') || (val[0] == '[object Object]'))){

        fragments.push('<li>[' + key + '] =></li>'); // add '[key] =>'
        recurse(val);            // call recurse to add a nested <ul>

      }else if(typeof(val)=='string'){  // catch strings, add double quotes

        fragments.push('<li>[' + key + '] = \"' + val + '\"</li>');

      }else if($.isArray(val)){         // catch arrays add [brackets]

        fragments.push('<li>[' + key + '] = [' + val + ']</li>');

      }else{                            // default: just print it.

        fragments.push('<li>[' + key + '] = ' + val + '</li>'); 
      }
    });
    fragments.push('</ul>'); // close </ul>
  }
  // end recursion function

  recurse(obj);            // call recursion
  return fragments.join('');    // return results
}  // end buildULfromOBJ()
于 2012-12-26T22:14:46.597 回答
1

为自己省去尝试使用 for 循环等的痛苦,并使用像json2html.com这样的客户端模板

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src='http://json2html.com/js/jquery.json2html-3.1-min.js'></script>

<ul id='out'></ul>

<script>

var data = 
{"Controls":[
    {
        "Object":"Button",
        "ButtonAttr": [{"x": "1","y": "2","width": "3","height": "4"}]
    },
    {
        "Object":"Image",
        "ButtonAttr": [{"x": "5","y": "6","width": "7","height": "8"}]
    },
    {
        "Object":"TextField",
        "ButtonAttr": [{"x": "9","y": "10","width": "11","height": "12"}]
    }
]};

var template = {"tag":"li","children":[
  {"tag":"span","html":"${Object}"},
  {"tag":"ul","children":[
    {"tag":"li","html":"x: ${ButtonAttr.0.x}"},
    {"tag":"li","html":"y: ${ButtonAttr.0.y}"},
    {"tag":"li","html":"width: ${ButtonAttr.0.width}"},
    {"tag":"li","html":"height: ${ButtonAttr.0.height}"}
   ]}
  ]};

$('#out').json2html(data.Controls,template);

</script>
于 2012-12-28T05:04:22.283 回答
0

您可以像第一个一样轻松地遍历第二个数组,如下所示:

$(document).on('click','#options li', function() {
    var index = $('#options li').index(this);
    $('#code').append('<li>' + data.Controls[index].Object + '</li>');

    // Create a new sub-UL to after the LI
    var $subUl = $(('<ul>')
    // Iterate through each attribute in ButtonAttr
    $.each(data.Controls[index].ButtonAttr, function(key, value){
        // Append a new LI with that attribute's key/value
        $subUl.append('<li>' + key + ':' + value + '</li>');
    });
    // Append that new sub-UL we made after the last LI we made
    $('#code li:last').after($subUl);

    //Shows Selected LI Index
    $('#optionsIndex').text("That was div index #" + index);
});
于 2012-12-26T22:09:24.303 回答
0

你可以这样做..使用$.each和 for in 循环

var str = '<ul>';
$.each(data.Controls, function(k, v) {
    str += '<li>' + v.Object + '</li><ul>';
    for(var kk in v.ButtonAttr[0]){
        str += '<li>' + kk + ':' + v.ButtonAttr[0][kk] + '</li>';
    }
    str += '</ul>';
});
str += '</ul>';

小提琴

或使用 2 个 $.each 循环

var str = '<ul>';
$.each(data.Controls, function(k, v) {
    str += '<li>' + v.Object + '</li><ul>';
    $.each(v.ButtonAttr[0],function(kk,vv){
      str += '<li>' + kk + ':' + vv + '</li>';
    });    
    str += '</ul>';
});
str += '</ul>';

小提琴

于 2012-12-26T22:39:06.483 回答