Alex H Hadik
Alex H Hadik

Reputation: 796

Creating a javascript variable from an external JSON file

I need to create a javascript variable that acts the same as if I hard coded

var test = [{"first" : "second"}];

and so on. However I need to load the data from an external, local .json file and set that data equal to the variable. I've done TONS of different attempts such as

var test;
jQuery.ajax({
        'async': false,
        'global': false,
        'url': "sequence.json",
        'dataType': "json",
        'success': function (data) {
            test = data;
        }
    });

However in all cases, the original test variable is never set as if it were hard coded to a JSON object. Often, I'm unable to even set the value of test at all. What would be a good way to go about this?

Upvotes: 0

Views: 993

Answers (1)

Md Mehedi Hasan
Md Mehedi Hasan

Reputation: 1792

if your ajax response is like data = [{"first" : "second"}]; then you can get you value like below. But json format is different then you have to specify your format first.

    var test;
    jQuery.ajax({
            'async': false,
            'global': false,
            'url': "sequence.json",
            'dataType': "json",
            'success': function (data) {
                data = [{"first" : "second"}];
                test = data;
                for(var i in test){
                console.log(test[i].first);
                alert(data[i]);
                }
            }
        });

Upvotes: 1

Related Questions