[Chartjs]-Load data from a JSON object into an array

4đź‘Ť

âś…

Try to debug your code with console.log() instead of alerts. Then you will see the following (open the browsers console with F12. To push the inner object to an array, you can just use Array.prototype.push().

var j = {"1":{"SME":"0","SAUDE":"0"}};
var arr = [];

$.each(j, function(key, val) {
    console.log(key); // 1
    console.log(val); // Object {SME: "0", SAUDE: "0"}
    console.log(val.SAUDE); // 0
    console.log(val.SME); // 0

    // add the object to the array:
    arr.push(val);     

});

0đź‘Ť

Your PHP script “getOrgaoAno.php” should like as below

<?php
 $data = array(/*YOUR DATA IS HERE*/);
 echo json_encode($data);
?>

No more extra spaces or any characters in the “getOrgaoAno.php” script before “<?php” and after “?>”, Otherwise JSON format error in JavaScript

And your JavaScript is ok, Just console from browser.

<script type="text/javascript">
 $.getJSON('getOrgaoAno.php', function(data) {
  $.each(data, function(key, val) {
   console.log(key); //Show me the index of the first array
   console.log(val); //Show me [OBJECT] in the console
  })
 });
</script>

Leave a comment