Home > Mobile >  Parse JSON object to ChartJS using object.keys/object.values
Parse JSON object to ChartJS using object.keys/object.values

Time:12-06

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?

CodePudding user response:

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];.

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,
    }
  }
};

console.info(document.getElementById('chart'))

new Chart(
    document.getElementById('chart'),
    config
);
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div  style="height:184px">
<canvas  id="chart" ></canvas>
</div>

If this is not the desired output, please update your question, with more specifiys

CodePudding user response:

the problem is that you are trying to access the first element of datapoints using datapoints[0], but datapoints is an object, not an array, so you can't access its elements using indices. Instead, you can use the Object.entries() method to get an array of key-value pairs from datapoints, and then access the first element of that array to get the key-value pair you want.

Here is an example of how you could do that:

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 [company, data] = Object.entries(datapoints)[0]; // get the first 
 key-value pair from datapoints

    const barchart = 
    document.getElementById('insider_positions_barchart').getContext('2d');
    const myBarChartAUD = new Chart(barchart, {
        type: 'bar',
        data: {
            labels: Object.keys(data),
            datasets: [{
                label: 'Net Activity',
                data: Object.values(data),
                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
                       }
                   }
               }
           }
       });
    }
}

This code uses Object.entries() to get an array of key-value pairs from datapoints, and then destructures that array to get the first key-value pair and assign its values to the company and data variables. Then, it uses the Object.keys() and Object.values() methods to get the keys and values from data and use them as the labels and data for the chart.

I hope this helps! Let me know if you have any other questions.

  • Related