1

I am pulling a JSON response into a ChartJS pie chart. Reading the docs it says that it needs to use datasets as:

datasets: [{
    data: [10, 20, 30]
}],

For my use case, the JSON is pulling in as:

{
    "action": "data_link_referer",
    "result": {
        "url_ending": "0",
        "data": [{
            "label": "Link1",
            "clicks": 3
        }, {
            "label": "Link2",
            "clicks": 3
        }, {
            "label": "Link3",
            "clicks": 2
        }]
    }
}

Inside the chart function I am pulling out the [data]. I would like to set the clicks as the value.

function drawChartPie(jsonObj) {
    var ctx = document.getElementById("myChartPie");
    var data = jsonObj["result"]["data"];

    var myPieChart = new Chart(ctx,{
        type: 'pie',
        data: {
            labels: data,

            datasets: [{
                label: 'Referers',
                data: data,
            }]
        },
    });
}

1 Answer 1

3

This will convert your data into the right format for ChartJS

function formatData(response) {
    let newFormat = {
        datasets: [{
            data: []
        }],
        labels: []
    };
    response.result.data.forEach(item => {
        newFormat.datasets[0].data.push(item.clicks);
        newFormat.labels.push(item.label);
    });
    return newFormat;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.