user2735719
user2735719

Reputation: 15

How to use a variable as js code?

I am trying to add the data into below function using jQuery (or highcharts). The question is how to embed the data into the javascript code without using eval since I will have to write all the code as string?

function pie(data)
{
  $(function () {
    $('#renderingdiv').highcharts({
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false
        },
        title: {
            text: 'Browser market shares at a specific website, 2010'
        },
        tooltip: {
            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
        },
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    color: '#000000',
                    connectorColor: '#000000',
                    format: '<b>{point.name}</b>: {point.percentage:.1f} %'
                }
            }
        },
        series: [**data**]
    });
});
};

data looks like:

{\
            type: 'pie',\
            name: 'Statuses',\
            data: [\
                [WSCH,   377]\
        ,\
                [WMATL,   4]\
        ,\
                [WAPPR,   349]\
        ,\
                [NCOMP,   3]\
        ,\
                [INPRG,   56]\
        ,\
                [COMP,   18]\
        ,\
                [CLOSE,   697]\
        ,\
                [APPR,   420]\
        \
            ]\
        }

Any idea please?

Upvotes: 0

Views: 97

Answers (1)

Pedro L.
Pedro L.

Reputation: 7556

This quick and dirty function converts your data to valid JSON and returns an object.

function parseData(data) {    
    data = data
        // remove \+line endings
        .replace(/\[\n\r]+/g, '') 
        // insert double quotes for keys
        .replace(/([\[{,])\s*(\w+)([,:])/g, '$1"$2"$3') 
        // replace values single quotes with double
        .replace(/(:)\s*'(\w+)\s*'/g, '$1"$2"'); 
    return JSON.parse(data);
}

Of course you should improve this to handle corner cases.

DEMO: http://jsfiddle.net/qq98D/2/ (result in console output)

But this is just a workaround. The real solution is to change the server output to return valid JSON.

Result (JSON encoded):

{"type":"pie","name":"Statuses","data":[["WSCH",377],["WMATL",4],["WAPPR",349],["NCOMP",3],["INPRG",56],["COMP",18],["CLOSE",697],["APPR",420]]}

Upvotes: 1

Related Questions