3

pretty new to javascript. Im trying to read a JSON file located on my localhost (http://localhost:8080/jsonData.json) and format it to be displayed using Chart.js.

Here is my JSON File:

[{"date": "1/02/16", "price":15.25},
{"date":"29/01/16", "price":15.35},
{"date":"28/01/16", "price":15.1}]

and my html file which will display the chart:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test Chart</title>
<script src="javascript/Chart.js"></script>
</head>
<body>
<canvas id="mycanvas" width="400" height="400"></canvas>
<script>
$.getJSON( "http://localhost:8080/jsonData.json", function( data ) {
    var chartjsData = [];
    var labels = [];
    $.each( data, function( key, val ) {
        labels.push(key);
        chartjsData.push(val);
      });

    var lineChartData = {
        labels : labels,
        datasets : [{
            fillColor : "rgba(220,280,220,0.5)",
            strokeColor : "rgba(220,220,220,1)",
            data : chartjsData
        }]
    };
    var myLine = new Chart(document.getElementById("mycanvas").getContext("2d")).Line(lineChartData);
});
</script>
</body>
</html>

basically when i run it i just get a blank screen with nothing displayed so I'm guessing its something to do with how I'm parsing the file, any help would be appreciated.

0

1 Answer 1

2

The JSON in that txt file is not a valid JSON object. You need to use regular quotes like so:

[{"date": "1/02/16", "price":15.25},
{"date":"29/01/16", "price":15.35},
{"date":"28/01/16", "price":15.1}];

Also you can use jQuery's $.getJSON function here:

var myJSON = $.getJSON( "example.json", function() {
  console.log( "success" );
})

see here: http://api.jquery.com/jquery.getjson/

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

3 Comments

still doesn't seem to fix the problem.. @Borna care to elaborate?
edited... let us know if it works now, sorry I didnt notice that right away
still no good, i didn't realise i had those quotes here but in my actual file they are the correct ones. i just updated the question to reflect my changes. Could it be that it can't access the son file in the ROOT webapp on my localhost?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.