我正在从服务器获取一些Json,以便在dom中动态构建一个表。 当有一个以上的对象的数据被作为对象返回的 一个这样的数组:如何处理有时在对象数组中返回的Json数据,有时只是一个对象?
{
"ProductList": {
"Products": [{
"ProductID": "1",
"Name": "ProdName"},
{
"ProductID": "2",
"Name": "ProdName2"}]
}
}
然而当存在它被简单地返回一个对象只有一个对象,而不是这样的数组:
{
"ProductList": {
"Products": {
"ProductID": "3",
"Name": "ProdName3"
}
}
}
所以,我一直在做的是检查,如果它是一个这样的数组:
if ($.isArray(productDetails.ProductList.Products) === true) {
for (i = 0; i < productDetails.ProductList.Products.length; i++) {
//Create the dom elements by accessing the object properties with [i]
//ie. productDetails.ProductList.Products[i].ProductsID
}
}
else {
//Create the dom elements by accessing the object properties w/o [i]
//ie. productDetails.ProductList.Products.ProductsID
}
它的工作原理,但我有很多Ø f代码,除了访问对象属性的方式完全相同,每当我改变一个我需要记住更改另一个或我会遇到问题。 在客户端是他们处理这个问题的更好方法吗?
将子对象作为数组返回是不是更好,无论它是1还是多个对象? – RJD22 2010-11-02 16:03:44