我知道这可能是之前被问到的,但是我试图找到答案 - 我猜我要么不理解一些答案,要么我正在看问题都错了。
我正在使用复杂的SLC环回查询 - 而api以下列格式返回JSON:
> [ {"id":"1","name":"John", "type":"commercial",
> "address":{"street1":"1 dalhousie lane", "street2":"some street"}},
> {"id":"2","name":"Jane", "type":"commercial",
> "address":{"street1":"15 dalhousie lane", "postcode":"1283833"}},
> {"id":"3","name":"Jack", "address":{"street1":"12 dalhousie lane",
> "postcode":"9383833", "geo":{"lat":"9393939","long":"99393939"}}}
如您所见,以下是问题 - 1.嵌套JSON - 多个级别 2.不一致/缺少键值, 例如:" id":" 2" - > "类型" - >失踪 例如:" id":" 3" - > "地址" - > "地理"
当我尝试使用KendoUI网格显示上面的json时,我会收到诸如 - 属性undefined之类的错误。我明白了,我可以探索的选项以及我应该做的事情 -
如果有人能够让我知道,如何向前迈进,那将会很棒。下面是网格的代码 -
$("#grid").kendoGrid({
dataSource: {
transport: {
read: {
url: apiurl,
dataType: "json",
}
}
},
columns: [
{
field: "id",
title: "User Id"
},
{
field: "name",
title: "User Name",
},
{
field: "type",
title: "User Type",
},
{
field: "address.street1",
title: "Street 1",
},
{
field: "address.street2",
title: "Street 2",
},
{
field: "address.postcode",
title: "Street 2",
},
{
field: "address.geo.lat",
title: "Latitude",
},
{
field: "address.geo.long",
title: "Longitude",
}
]
});
答案 0 :(得分:4)
您可以使用 column templates :
columns: [
{
field: "id",
title: "User Id"
},
{
field: "name",
title: "User Name",
},
{
field: "type",
title: "User Type",
template: function(dataItem) {
return dataItem.type ? kendo.htmlEncode(dataItem.type) : "";
}
},
{
field: "address",
title: "Street 1",
template: function(dataItem) {
return dataItem.address.street1 ? kendo.htmlEncode(dataItem.address.street1) : "";
}
},
{
field: "address",
title: "Street 2",
template: function(dataItem) {
return dataItem.address.street2 ? kendo.htmlEncode(dataItem.address.street2) : "";
}
},
{
field: "address",
title: "Post Code",
template: function(dataItem) {
return dataItem.address.postcode ? kendo.htmlEncode(dataItem.address.postcode) : "";
}
},
{
field: "address",
title: "Latitude",
template: function(dataItem) {
return dataItem.address.geo && dataItem.address.geo.lat ? kendo.htmlEncode(dataItem.address.geo.lat) : "";
}
},
{
field: "address",
title: "Longitude",
template: function(dataItem) {
return dataItem.address.geo && dataItem.address.geo.long ? kendo.htmlEncode(dataItem.address.geo.long) : "";
}
}
]
每个模板都是一个检查字段是否存在的函数,然后返回字段值或空字符串。
正在使用 DEMO
答案 1 :(得分:1)
另一个选项是使用schema.parse方法来处理为缺少的字段添加默认值。以下是文档的链接 - http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configuration-schema.parse
<script>
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "yoururl",
dataType: "jsonp"
}
},
schema: {
parse: function(response) {
var items = [];
for (var i = 0; i < response.length; i++) {
var item = response[i];
if(!item.address.geo){
if(!item.address.geo.lat){
item.address.geo.lat = 0.0;
}
}
items.push(item);
}
return items;
}
}
});
dataSource.fetch(function(){
var data = dataSource.data();
var product = data[0];
console.log(product.name);
});
</script>
希望这有帮助。
瓦德