使用jquery将嵌套JSON分配给li

时间:2012-12-26 22:05:52

标签: javascript jquery json listitem

我正在尝试使用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 个答案:

答案 0 :(得分:1)

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

How to handle comma separated objects in json? ( [object Object],[object Object] )

你想要一个启动&lt; ul&gt;的递归函数并添加&lt; li&gt;对于列表中的每个项目。它还测试项目,如果它们本身就是列表,它会将该数据作为参数调用自身。每次从函数中调用函数时,都会得到一个&lt; ul&gt;在&lt; ul&gt;内。

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

答案 1 :(得分: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>

答案 2 :(得分: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);
});

答案 3 :(得分:0)

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

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>';

FIDDLE

或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>';

FIDDLE