ashutosharma24
ashutosharma24

Reputation: 5

How to use output of JSON.parse() as a input of HTML charts' data field?

I am trying to draw HTML graphs from excel/JSON data which is available as an external file on local.

Code snippet: data.json file

[{
"Name": "ABC",
"Subject1": "Physics",
"Subject2": "Chemistry",
"Subject3": "Maths",
"Optional": "Biology",
},
{
"Name": "XYZ",
"Subject1": "Economics",
"Subject2": "Accounts",
"Subject3": "Maths",
"Optional": "IT",
}]

Code snippet: js file

var actual_JSON;
function loadJSON(callback) {   
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', 'data.json', true); 
    xobj.onreadystatechange = function () {
        if (xobj.readyState == 4 && xobj.status == "200") {
            callback(xobj.responseText);
        }
    };
    xobj.send(null);  
}

function init() {
    loadJSON(function(response) {
        // Parse JSON string into object
        actual_JSON = JSON.parse(response);
    });
}

Now, the output of actual_JSON is returning data as objects. And if I pass actual_JSON in the data field like :

var data = actual_JSON;

var chart = new Chart(ctx, {
    data: data,
    type: 'line',
    options: options
});

I am not getting any value. What can be done to get the values?

Upvotes: 0

Views: 172

Answers (1)

Shreyan Mehta
Shreyan Mehta

Reputation: 550

you could use create another object using data of this object, that should be just a regular json

EX:

var charData = {};
Object.keys(actual_JSON).forEach((key) => {
charData[key] = actual_JSON[key]
})

try use charData

Upvotes: 1

Related Questions