1

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 ...

2 Answers 2

1

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? , 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.

Sign up to request clarification or add additional context in comments.

Comments

0

The first format doesn't actually contain a list, but an object hash. You need to modify your code as follows to work with it.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.