1

I am trying to use a simple $.ajax GET to retrieve data from an API, and bind it to Google Charts. My API returns this data:

enter image description here

This is the format that the Google documentation uses to declare the datatable in-page. However, when creating the table from downloaded data, the console shows:

Error: Not an array

Current code is:

function LoadJsonData() {
    $.ajax({
        type: 'GET',
        url: '/api/Test',
        dataType: "json",
        success: function (data) {
            var dt0 = new google.visualization.arrayToDataTable(data, false);
            var chart0 = new google.visualization.PieChart(document.getElementById('ContentPlaceHolderBody_ctl02'));
            var options0 = { title: 'Some title', width: 400, height: 300 };
            chart0.draw(dt0, options0);
        }
    });
}

google.charts.load('current', { packages: ['corechart', 'table'] });
google.charts.setOnLoadCallback(LoadJsonData);
EvilDr
  • 8,943
  • 14
  • 73
  • 133

2 Answers2

1

google.visualization.arrayToDataTable accepts an array of arrays []:

From the docs

var data = google.visualization.arrayToDataTable([
       ['Employee Name', 'Salary'],
       ['Mike', {v:22500, f:'22,500'}], // Format as "22,500".
       ['Bob', 35000],
       ['Alice', 44000],
       ['Frank', 27000],
       ['Floyd', 92000],
       ['Fritz', 18500]
      ],
      false); // 'false' means that the first row contains labels, not data.

Your json/js object is not in the same format as above, it's an array of objects {}

[{},{}...etc.]

Reformat your json into the correct format. Something along the lines of:

[["FirstName", "count"],
["Bob", "60"],
["Wendy", "4"]]

Note: the first array (["FirstName", "count"]) contains the labels. the following array(s) contain the data. This will be easier to do server side. If you want to do it client side please read Access / process (nested) objects, arrays or JSON

Community
  • 1
  • 1
Liam
  • 27,717
  • 28
  • 128
  • 190
  • Its as if the function won't accept the data contents, because they are not declared inside the function call itself. – EvilDr May 17 '17 at 11:41
  • It sounds like (It's unclear without a [MCVE](http://stackoverflow.com/help/mcve)) that data isn't an array. Check that data is how you expect it look as above, what you put in your comment should work. PS remember to pass `false` into the call to `arrayToDataTable` if your passing the column headers in the first array @EvilDr – Liam May 17 '17 at 12:09
  • 1
    I think I know what your issue is in json you need to use `"`. So format your **json** `[["FirstName", "count"],["Bob", "60"]..etc]` – Liam May 17 '17 at 12:15
  • I think you might have it, there. Is there a way to do this in JQuery/JS, as I don't want to hack the API output logic if it will break stuff elsewhere? – EvilDr May 17 '17 at 13:07
  • Updateing the API wouldn't be a hack. It should be returning the data in the above format – Liam May 17 '17 at 13:14
  • Is `data` an object or a string? `[['firstname',...]` is a valid javascript object but an **invalid json string** – Liam May 17 '17 at 13:27
  • If data is an object, and it is an array of arrays, everything should now be working then? – Liam May 17 '17 at 14:07
  • The error is *Error: Not an array*. I've updated the question to remove all the noise and focus on your advice so far. Sorry if I've backtracked; my head is spinning – EvilDr May 17 '17 at 14:35
  • Are you 100% sure `data` **is an object**? Because your not parsing it, so if your don't specify the right headers it will come out as a string. Your example only shows the HTTP response, what happens if you debug your javascript and add a watch to `data`? This for me, is still suggesting that `data` is not an object but a string. – Liam May 17 '17 at 14:51
  • 1
    Sorry, you are quite correct, it is a string. God knows how I ended up seeing "object" in the alert earlier. I've been staring at this far too long. – EvilDr May 17 '17 at 15:04
  • I'd imagine your not passing the `application/json` header value with your HTTP request. If you don't tell jQuery "this is json" it won't parse it. The other option is to use `JSON.parse` – Liam May 17 '17 at 15:10
  • See this question [jQuery won't parse my JSON from AJAX query](http://stackoverflow.com/questions/249692/jquery-wont-parse-my-json-from-ajax-query) – Liam May 17 '17 at 15:11
-2

Your first row, {"FirstName":"Bob", "Count" : 34} is a JSON object not an array.

Your attempts to JSON.parse the data in your success function will have made an attempt to parse the whole data object.

You you want to parse each item, try the following

success: function (data) {
         $.each(data, function(i, value){
              var dt0 = new google.visualization.arrayToDataTable(JSON.parse(value));
              var chart0 = new google.visualization.PieChart(document.getElementById('ContentPlaceHolderBody_ctl02'));
             var options0 = { title: 'Some title', width: 400, height: 300 };
             chart0.draw(dt0, options0);
          }
    }, 
  • An example would be helpful please, as the JQuery documentation simply shows simple transformations on the array values. – EvilDr May 17 '17 at 10:40
  • I've updated my answer. I don't think the map function I suggested before is quite necessary, I noticed you weren't iterating through the items of your request and think this may be why you couldn't just parse each datum! – ADoorMarkedPirate May 17 '17 at 11:07
  • 1
    There's a bug in your code; it $each should be terminated with `});` not just `}`. Anyway, it produces the error *JSON.parse: unexpected character at line 1 column 2 of the JSON data* – EvilDr May 17 '17 at 11:29
  • `value` would still be in an incorrect format and, yes, this is invalid syntax – Liam May 17 '17 at 12:12