i have a json data and trying to parse it with d3.json function.The format of the data is like this .
{
"StoreVisitGraphCount": {
"list": {
"count": 23,
"date": "01-2013"
},
"parameters": {
"format": "m-Y",
"point": 10,
"type": "mo"
}
}
}
i am trying to parse it with the following function
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;
});
its showing an error say “Uncaught TypeError: Object # has no method ‘forEach'”
but after modifying the json data to
{
"StoreVisitGraphCount": {
"list": [{
"count": 23,
"date": "01-2013"
}],
"parameters": {
"format": "m-Y",
"point": 10,
"type": "mo"
}
}
}
making the list an array .. it parsed sucessfully showing no error..
as when there is only one data in list array the rest creates the json like the first format but when there is more than one list data
it creates the json like second format… how to solve or write function in d3.js so that it can parse the first format too …
If you want to deal with both the data formats, the most straight forward way to do it is checking whether the
data.StoreVisitGraphCount.listis anArrayor anObject. Taking a cure from the question: How to check if a JSON response element is an array? , the most reliable way to do it is:Then your code would read:
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.