how to use JSON Data in chart.js?

34,100

Solution 1

I am not quite sure if you mean this:

var chartjsData = [];
for (var i = 0; i < json.length; i++) {
    chartjsData.push(json[i].present_worth);  
}

http://jsfiddle.net/rnX2Z/1/

Otherwise comment ;)

Solution 2

So this a JSON data example,

var data = '{"name":"tom","Second":"smith","age":"20","height":"180"}'

Create a Variable to Parse the data

var obj9 = JSON.parse(data);

Then make another Variable to store your specific data. (.age, this is relative to your data set, eg .name, .height)

var cat = obj9.age;

Then you can use the the variable cat in your graph data.

data : [cat9,randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]

Hope that helps.

Find out more about JSON http://www.w3schools.com/json/default.asp

Share:
34,100
Sajan Shakya
Author by

Sajan Shakya

Updated on August 02, 2022

Comments

  • Sajan Shakya
    Sajan Shakya almost 2 years

    hi i have been trying to use data from MYSQL database and use them to create graphical chart with chart.js. i encoded data into JSON data( through a php file name data1.php), now i need to convert these Json data back to array using Jquery or javascript.. i dont have much knowledge about AJAX.. so could u help me out??

    data1.php produces JSON data as

    [{"company_name":"project A","present_worth":"81531.946062978"},{"company_name":"project B","present_worth":"67313.916593765"},{"company_name":"project c","present_worth":"92440.723376746"}]
    

    i need value of present_worth in an array

    this is the script used to create bargraph.. instead of custom data (for eg data : [65,59,90,81,56,55,40])given here i want an array here with JSON data.

    <script type="text/javascript">
    
            function bar(){
    
            var barChartData = {
                labels :["January","February","March","April","May","June","July"],datasets : [
                    {
                        fillColor : "rgba(220,280,220,0.5)",
                        strokeColor : "rgba(220,220,220,1)",
                        data : [65,59,90,81,56,55,40]
    
                    },
                    {
                        fillColor : "rgba(151,187,205,0.5)",
                        strokeColor : "rgba(151,187,205,1)",
                        data : [28,48,40,19,96,27,100]
                    }
                ]
            };
        var myLine = new Chart(document.getElementById("canvas").getContext("2d")).Bar(barChartData);
    }
    </script>