如何使用嵌套的Json填充Kendo UI网格?

时间:2013-06-21 08:50:17

标签: javascript json kendo-ui kendo-grid

如何使用嵌套的JSON填充Kendo UI网格。

我的意思是我的JSON就像

var myJson:
    [{"oneType":[
        {"id":1,"name":"John Doe"},
        {"id":2,"name":"Don Joeh"}
    ]},
    {"othertype":"working"},
    {"otherstuff":"xyz"}]
}];

我希望Kendo UI Grid的列为Id,Name,OtherType和OtherStuff。

提前致谢。

2 个答案:

答案 0 :(得分:9)

对于复杂的JSON结构,您可以使用schema.parse

var grid = $("#grid").kendoGrid({
    dataSource : {
        data    : [
            {
                "oneType": [
                    {"id": 1, "name": "John Doe"},
                    {"id": 2, "name": "Don Joeh"}
                ]
            },
            {"othertype": "working"},
            {"otherstuff": "xyz"}
        ],
        pageSize: 10,
        schema  : {
            parse : function(d) {
                for (var i = 0; i < d.length; i++) {
                    if (d[i].oneType) {
                        return d[i].oneType;
                    }
                }
                return [];
            }
        }
    }
}).data("kendoGrid");

如果您稍微将JSON更改为:

{
    "oneType"   : [
        {"id": 1, "name": "John Doe"},
        {"id": 2, "name": "Don Joeh"}
    ],
    "othertype" : "working",
    "otherstuff": "xyz"
}

然后你可以使用:

var grid = $("#grid").kendoGrid({
    dataSource: {
        data    : {
            "oneType"   : [
                {"id": 1, "name": "John Doe"},
                {"id": 2, "name": "Don Joeh"}
            ],
            "othertype" : "working",
            "otherstuff": "xyz"
        },
        pageSize: 10,
        schema  : {
            data: "oneType"
        }
    }
}).data("kendoGrid");

答案 1 :(得分:0)

我只是想根据OnaBai提交另一个答案。

http://jsfiddle.net/L6LwW/17/

HTML:

<script id="message-template" type="text/x-kendo-template">
  #for (var i = 0; i
  < ddl.length; i++) {# <li><span>#=ddl[i].value#</li>
    #}#
    </script>

<div id="grid"></div>

JS:

var grid = $("#grid").kendoGrid({
  dataSource: {
    data: [
      [{
        "id": 1,
        "name": "John Doe",
        "ddl": [{
          "key": 1,
          "value": "hello"
        }, {
          "key": 1,
          "value": "hello"
        }]
      }, {
        "id": 2,
        "name": "Don Joeh",
        "ddl": [{
          "key": 1,
          "value": "hello"
        }, {
          "key": 1,
          "value": "hello"
        }]
      }]
     ],
    pageSize: 10,
    schema: {
      parse: function(d) {
        for (var i = 0; i < d.length; i++) {
          if (d[i]) {
            return d[i];
          }
        }
        return [];
      }
    }
  },
  columns: [{
      field: "id",
      title: "ID"
    }, {
      field: "name",
      title: "Name"
    }, {
      field: "ddl",
      title: "DDL",
      width: "180px",
      template: kendo.template($("#message-template").html())
    } //template: "#=ddl.value#" }
  ]
}).data("kendoGrid");