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

CresCent
  • 49
  • 7

3 Answers3

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.

Rx9
  • 101
  • 4
  • For this purpose you do not even need to escape you could simply use ````var newlabels= '["label1", "label2", "label3", "label4"]';```` – michaelT Oct 02 '20 at 05:09
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)); 
davidhu
  • 9,523
  • 6
  • 32
  • 53
2

JSON does not support single quotes, so this code:

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

Becomes this:

 var newlabels= '["label1", "label2", "label3", "label4"]';
Abbas
  • 1,118
  • 1
  • 11
  • 25