1

I have 2 var below to update datasets and labels of my chart.

function updateChart(){

   var newdatasets= "[10, 20, 30, 40]";
   var newlabels= "['label1', 'label2', 'label3', 'label4']";

   myChart.data.datasets[0].data = JSON.parse(newdatasets); //this work
   myChart.data.labels = JSON.parse(newlabels);             //this does not work
}

Why JSON.parse work with newdatasets but wont work with newlabels? The JSON.parse(newdatasets) updated the chart datasets successfully but JSON.parse(newlabels) fail to update chart labels. What can I do to fix this?

Dont ask me to change the var value to ['label1', 'label2', 'label3', 'label4'] without the ". I know this will work but I want the chart to change from that kind of var value.

Thank you for any help..

3 Answers 3

2

The newlabels is having wrong JSON string format. Let change ' with " with escape.

This will work:

var newlabels= "[\"label1\", \"label2\", \"label3\", \"label4\"]";
myChart.data.labels = JSON.parse(newlabels);

The variable newdatasets works with JSON.parse because its elements are number.

Sign up to request clarification or add additional context in comments.

1 Comment

For this purpose you do not even need to escape you could simply use var newlabels= '["label1", "label2", "label3", "label4"]';
2

To be valid JSON, you need double-quotes. So the code below works.

Both examples work. You just need double quotes as part of the string itself.

var newlabels2= '["label1", "label2", "label3", "label4"]';
console.log(JSON.parse(newlabels2)); 

var newlabels3= "[\"label1\", \"label2\", \"label3\", \"label4\"]";
console.log(JSON.parse(newlabels3)); 

Comments

2

JSON does not support single quotes, so this code:

 var newlabels= "['label1', 'label2', 'label3', 'label4']";

Becomes this:

 var newlabels= '["label1", "label2", "label3", "label4"]';

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.