Hey there, I'm new to programming so please bear with me XD. I've been struggling for 2 days trying to figure this out with no luck.
So here's the deal - I have a chart in JavaScript that is pulling data from a file called test.json, which is located in the same directory as the chart file:
data2020 = '[0,0,0,0,0,202,50857,116823,113280,109400,99846,83975]';
data2021 = '[58578,15864]';
I recently learned how to update the data and realized that my JSON format was not standard when using this script:
file_put_contents('test.json', $newJsonString);
The updated JSON format now looks like this:
[{"data2020":[0,0,0,0,0,202,50857,116823,113280,109400,99846,83975],"data2021":[58578,15864]}]
But now my chart can't read this new JSON file. After some investigation, I suspect the issue may be with my chart setup since I only have this simple configuration:
data: {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
datasets: [{
label: "Produksi 2020 : ",
lineTension: 0.3,
backgroundColor: "rgba(78, 115, 223, 0.05)",
borderColor: "rgba(235, 180, 39, 1)"
// more dataset configurations...
data: JSON.parse(data2020),
},
Someone suggested adding both scripts to my PHP file as follows:
<script src="../js/test.json"></script>
<script src="../js/chart.js"></script>
Basically, all I did was use JSON.parse and nothing else. I understand that I need to convert my JSON file into an array and use that array in the data. But I'm stuck on figuring out how to do that. So, the question is pretty straightforward - how do I convert a JSON file to an array in JavaScript?
I tried reading through this link for help, but it's still a bit confusing for me XD: How to read an external local JSON file in JavaScript?