2013-02-05 89 views
1

我有一个json数据并试图用d3.json函数解析它。数据的格式是这样的。d3.js无法解析json数据

{ 
"StoreVisitGraphCount": { 
    "list": { 
     "count": 23, 
     "date": "01-2013" 
    }, 
    "parameters": { 
     "format": "m-Y", 
     "point": 10, 
     "type": "mo" 
    } 
    } 
} 

我试图用下面的函数解析它

d3.json("http://localhost:8080/data- services/rest/storeVisitsGraph/20120101,20131231,-1", function(error, data) { 
data.StoreVisitGraphCount.list.forEach(function(d) { 
d.date = parseDate(d.date); 
d.count = +d.count; 
}); 

其显示错误说“遗漏的类型错误:对象#有没有一种方法‘的forEach’” 但JSON数据修改后

{ 
"StoreVisitGraphCount": { 
    "list": [{ 
     "count": 23, 
     "date": "01-2013" 
    }], 
    "parameters": { 
     "format": "m-Y", 
     "point": 10, 
     "type": "mo" 
    } 
    } 
} 

使得列表中的一个阵列..它成功地解析的表示作为当在列表阵列只有一个数据的其余部分不产生错误.. json类似于第一种格式,但是当有多个列表数据时 它创建了类似于第二种格式的json ...如何在d3.js中解析或编写函数,以便它可以解析第一种格式...

回答

1

如果你想同时处理的数据格式,最直接的方式做到这一点是检查data.StoreVisitGraphCount.list是否是ArrayObject。从这个问题以治愈:How to check if a JSON response element is an array?,最可靠的方法来做到这一点是:

function isArray(what) { 
    return Object.prototype.toString.call(what) === '[object Array]'; 
} 

那么你的代码将改为:

d3.json(..., function(error, data) { 
    if (!isArray(data.StoreVisitGraphCount.list)) { 
    data.StoreVisitGraphCount.list = [ data.StoreVisitGraphCount.list ]; 
    } 

    data.StoreVisitGraphCount.list.forEach(function(d) { 
    d.date = parseDate(d.date); 
    d.count = +d.count; 
    }); 
}); 

然而,这并不是一个非常一致的API设计。如果API在您的控制之下(您正在运行localhost的服务),那么请考虑将其更改为一致并在每种情况下返回一个列表。

0

第一种格式实际上并不包含一个列表,而是一个对象散列。您需要按照以下方式修改您的代码以使用它。

d3.json(..., function(error, data) { 
    data.StoreVisitGraphCount.list.date = parseDate(data.StoreVisitGraphCount.list.date); 
    data.StoreVisitGraphCount.list.count = +data.StoreVisitGraphCount.list.count; 
});