Search code examples
zingchart

Zing chart load webapi Json data Issue


Am trying to load Zingchart using JSON data retrieved from Webapi.

The sample data is like this

$scope.testValues = [{"text":"Sample1","values":"[465]"},{"text":"Sample2","values":"[288]"}];

But ZingChart is expecting the values to be..

[{"text":"Sample1","values":[465]},{"text":"Sample2","values":[288]}];

(Without quotes in the values*)

and because of this am getting a different output in UI as the chart is showing 2 or 3 times

enter image description here

Can you please let me know how to bind a JSON data from webapi to chart dynamically ?


Solution

  • You have to replace the quotes before and after the brackets[] using:

        var eventlist = JSON.stringify(testValues);
        var eventstring = new String();
        eventstring = eventlist.replace(/"\[/g, '[');
        eventstring = eventstring.replace(/\]"/g, ']');
    

    So your final code is:

      var testValues = [{"text":"Sample1","values":"[465]"},{"text":"Sample2","values":"[288]"}];
      var eventlist = JSON.stringify(testValues);
      var eventstring = new String();
      eventstring = eventlist.replace(/"\[/g, '[');
      eventstring = eventstring.replace(/\]"/g, ']');
        
    var myConfig = {
     	type: 'pie', 
    	series: JSON.parse(eventstring)
    };
    
    zingchart.render({ 
    	id: 'myChart', 
    	data: myConfig, 
    	height: '100%', 
    	width: '100%' 
    });
    html, body {
    	height:100%;
    	width:100%;
    	margin:0;
    	padding:0;
    }
    #myChart {
    	height:100%;
    	width:100%;
    	min-height:150px;
    }
    .zc-ref {
    	display:none;
    }
    <!DOCTYPE html>
    <html>
    	<head>
    		<script src= "https://cdn.zingchart.com/zingchart.min.js"></script>
    	</head>
    	<body>
    		<div id="myChart"><a class="zc-ref" href="https://www.zingchart.com">Powered by ZingChart</a></div>
    	</body>
    </html>