Reputation: 91
I'm trying to show data from a JSON file to ChartJS, however, my JSON structure is different to what I have seen in previous relatable questions. Check JSON below:
{
"AAPL": [
{
"Q1": -26986,
"Q2": -168099,
"Q3": -137101,
"Q4": -561990
}
]
}
My code is an attempt to use the keys as labels and the values as data:
const xmlhttp4 = new XMLHttpRequest();
const url4 = 'https://api.npoint.io/ee3b3d406810c46c44e0';
xmlhttp4.open('GET', url4, true);
xmlhttp4.send();
xmlhttp4.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
const datapoints = JSON.parse(this.responseText);
const data1 = datapoints[0]
const barchart = document.getElementById('insider_positions_barchart').getContext('2d');
const myBarChartAUD = new Chart(barchart, {
type: 'bar',
data: {
labels: Object.keys(data1),
datasets: [{
label: 'Net Activity',
data: Object.values(data1),
backgroundColor: [
'rgba(0, 255, 255, 0.2)',
],
borderColor: [
'rgba(0, 255, 255, 1)',
],
borderWidth: 3
}]
},
options: {
plugins: {
legend: {
display: false
}
},
maintainAspectRatio: false,
scales: {
y: {
ticks: {
color: "white"
},
grid: {
display: false
}
},
x: {
ticks: {
color: "white"
},
grid: {
display: false
}
}
}
}
})
}
}
I'm not sure why this isn't working, I'm guessing it's to do with how I'm calling the keys & values. Unless I should change the JSON structure perhaps?
Upvotes: 1
Views: 111
Reputation: 14785
I'm not 100% sure, what for an output you want/expect, but I would have to say, if you want to display the quarters, you would have to get the values from here data1["AAPL"][0];
, in this specific case.
Here a short demo showcasing it:
let data1= { "AAPL": [{
"Q1": -26986,
"Q2": -168099,
"Q3": -137101,
"Q4": -561990
}]};
// extracting only the needed data
let initialData = data1["AAPL"][0];
const data = {
labels: Object.keys(initialData),
datasets: [{
label: 'Dataset 0',
data: Object.values(initialData),
backgroundColor: '#B0D3FF',
barThickness: 20,
}]
};
const config = {
type: 'bar',
data: data,
options: {
plugins: {
title: {
display: false,
},
legend: {
display: false
}
},
responsive: true,
maintainAspectRatio: false,
interaction: {
intersect: false,
}
}
};
new Chart(
document.getElementById('chart'),
config
);
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div class="chart" style="height:184px">
<canvas id="chart" ></canvas>
</div>
If this is not the desired output, please update your question, with more specifics
Upvotes: 1