If you want to deal with both the data formats, the most straight forward way to do it is checking whether the data.StoreVisitGraphCount.list is an Array or an Object. Taking a cure from the question: How to check if a JSON response element is an array?How to check if a JSON response element is an array? , the most reliable way to do it is:
function isArray(what) {
return Object.prototype.toString.call(what) === '[object Array]';
}
Then your code would read:
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;
});
});
However, that is not a very consistent API design. If the API is in your control (you are running the service from localhost), then consider changing it to be consistent and return a list in every case.