Search code examples
javascriptjsonparsinggetjson

Loading local json file and assigning the result to a variable


i'm having problem with paresing a json file, i don't now where is the problem, hope you help me.

<script type="text/javascript">
var d;
$.getJSON("empl-estab.json", function (data) {
d=data;
});
console.log(d);
var chart = Highcharts.chart('container', {
title: {
                        text: 'Statistiques'
                    },
                    subtitle: {
                        text: 'Plan'
                    },
                    xAxis: {
                        categories: d.categories,
                    },
                    series: [{
                            type: 'column',
                            colorByPoint: true,
                            data: d.data,
                            showInLegend: false
                        }]

                });
</script>

the error is : d is undefined


Solution

  • Place all the code related to the response result inside getJSON's callback function. This is happening because all the code outside are executing before the request is complete. Hence d is undefined.

    var d;
    $.getJSON("empl-estab.json", function (data) {
      d=data;
      console.log(d);
      var chart = Highcharts.chart('container', {
      title: {
            text: 'Statistiques'
        },
        subtitle: {
            text: 'Plan'
        },
        xAxis: {
            categories: d.categories,
        },
        series: [{
                type: 'column',
                colorByPoint: true,
                data: d.data,
                showInLegend: false
            }]
    
      });
    });