Reputation: 141
I am trying to read JSON file like this:
[166.1086159,153.6025535,109.9585098,149.0443019,121.9854975,136.2424609,68.07276721,75.02149785,112.0627478]
I deleted most of the numbers inside. I have around 200 of json files like that(depending on which button you press), so the question is how do I save this array to a variable? I've been banging my head about this for quite some time!
All help appreciated!
<!doctype html> <html> <head> <title>Bar Chart</title> <script src="./Chart.js/Chart.js"></script> </head> <body> <div style="width: 80%"> <canvas id="canvas" height="300" width="800"></canvas> </div> <script> function reqListener () { console.log(this.responseText); current = JSON.parse(this.responseText); }
> var oReq = new XMLHttpRequest();
> oReq.onload = reqListener;
> oReq.open("get", file, true);
> oReq.send();
var barChartData = { labels : ["501", "502", "503", "504", "505", "506", "507", "508", "509", "510", "511", "512", "513", "514", "515", "516", "517", "518", "519", "520", "521", "522", "523", "524", "525", "526", "527", "528", "529", "530", "531", "532", "533", "534", "535", "536", "537", "538", "539", "540", "541", "542", "543", "544", "545", "546", "547", "548", "549", "550", "551", "552", "553", "554", "555", "556", "557", "558", "559", "560", "561", "562", "563", "564", "565", "566", "567", "568", "569", "570", "571", "572", "573", "574", "575", "576", "577", "578", "579", "580",], datasets : [ { fillColor : "rgba(151,187,205,0.5)", strokeColor : "rgba(151,187,205,0.8)", highlightFill : "rgba(151,187,205,0.75)", highlightStroke : "rgba(151,187,205,1)", data : current } ] } window.onload = function(){ var ctx = document.getElementById("canvas").getContext("2d"); window.myBar = new Chart(ctx).Bar(barChartData, { responsive : true }); } </script> </body> </html>
Upvotes: 0
Views: 819
Reputation: 781096
If you load the file contents into a string variable, you use:
var string = '[166.1086159,153.6025535,109.9585098,149.0443019,121.9854975,136.2424609,68.07276721,75.02149785,112.0627478]';
var array = JSON.parse(string);
console.log(array);
If the data is in a file on your server, you can use AJAX to read it. See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest for examples of how to use the XMLHttpRequest
interface in Javascript for this.
Upvotes: 2
Reputation: 486
Just use JSON.parse and pass in the file text as a string and then save it to a variable
var fileText = '';//load the file text
var jsonData = JSON.parse(fileText);
Upvotes: 1