简体   繁体   中英

Displaying Table has no Columns using Google Charts

Trying to change the format of JSON to make it readable for Google charts. The JSON content is working fine and currently displaying this on the browser:

[["name","cost"],["godzilla",12],["harry potter",12]]

The Task is being performed by a spring controller

  @RequestMapping(value = "api/productschart", method = RequestMethod.GET)

    public @ResponseBody
    String listProductsJsonChart () throws JSONException {

    JSONArray ProductArray = new JSONArray();
    JSONArray ProductHeader = new JSONArray();

    ProductHeader.put("id");
    ProductHeader.put("cost");

    ProductArray.put(ProductHeader);


    for (Product product : productRepository.findAll()) {
        JSONArray ProductJSON = new JSONArray();

        ProductJSON.put(product.getId());
        ProductJSON.put(product.getCost());

        ProductArray.put(ProductJSON);
    }
    return ProductArray.toString();
}

The JavaScript section

  <script type="text/javascript">

google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {

  var jsonData = $.ajax({
    url: "http://localhost:8081/api/productschart",
    dataType: "json",
    async: false
  }).responseText;


  var data = new google.visualization.DataTable(jsonData);



  var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));

  chart.draw(data);
}
</script>

The examples on Google's pages use single quotes because they use JavaScript to build objects and JavaScript supports both single and double quotes. JSON, on the other hand, requires double quotes.

table has no columns

From the example at https://developers.google.com/chart/interactive/docs/gallery/columnchart#Data_Format , I think your JSON should look like this:

[["id","cost"],["1",12]]

ie the first item in the data part of the array needs to be a string. In your case, it's a number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM