Reputation: 3303
I'm beginning to use html charts to display data coming from json
files. Up until five days ago, I very rarely did anything with html charts. But now that's all I do.
So I'm using an anychart
chart, and I've been trying to find a way to populate the chart with a 'json` file.
After much trial-error, I was able to somewhat separate the data and move it to a json
file. The problem is that the file's not completely json
string.
As you can see, MyFile.json has the json
string and some chart components. I would like my json file to be only json data; everything else should be in the html, another javascript, or anywhere else. But it cannot be in the json
file.
In other words, MyFile.json should only include this:
{"x": "January","value": 10000},{"x": "February","value": 12000}, {"x": "March","value": 18000}]
Is this possible? Any help is appreciated. Thanks.
Here's MyFile.json:
{
"chart": {
"type": "line",
"series": [{
"seriesType": "spline",
"data": [{
"x": "January",
"value": 10000
}, {
"x": "February",
"value": 12000
}, {
"x": "March",
"value": 18000
}]
}],
"container": "container"
}
}
And here's my html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.anychart.com/js/7.13.1/anychart-bundle.min.js"></script>
<link rel="stylesheet" href="https://cdn.anychart.com/css/latest/anychart-ui.min.css">
</head>
<body>
<div id="container"></div>
</body>
</html>
<script>
$(document).ready(function(){
$.getJSON('MyFile.json', function(data) {
console.log(data);
anychart.fromJson(data).draw();
});
});
</script>
Upvotes: 2
Views: 680
Reputation: 781
One approach is to append each chart into the container first and then set jquery data with the series.
$.getJSON('MyFile.json', function (charts) {
for (var i = 0, len = charts.length; i < len; i++) {
$('#container').append('<div id="chart_' + i + '"></div>');
$('chart_' + i).data('series', charts[i].series.data);
}
});
Upvotes: 0
Reputation: 22247
If I understood your question correctly... There might be a way within Anycharts to do this in a better way (like assign an object as the "settings" then assign a different one wit the "data"), but here's one way that you could implement this yourself:
JSON file:
[{
"x": "January",
"value": 10000
}, {
"x": "February",
"value": 12000
}, {
"x": "March",
"value": 18000
}]
AJAX request in javascript file:
$(document).ready(function(){
$.getJSON('MyFile.json', function(data) {
var wrapper = {
"chart": {
"type": "line",
"series": [{
"seriesType": "spline",
"data": data // adding the ajax response data
}],
"container": "container"
}
};
anychart.fromJson(wrapper).draw();
});
});
Upvotes: 2
Reputation: 3191
You can embed json data in a html element using data-*
attributes.
Upvotes: 0