Click here to Skip to main content
15,940,246 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
JavaScript
var persons;
        $(function () {
            $.getJSON("person.json", function(data){ persons = JSON.stringify(data); 
                console.log("This is inside: "+ persons); });
                console.log("This is outside" + persons);
            }
            getJSONData();
        });


i want to get and store data from local file(person.json) into a variable at the beginning. But the result is:
This is outside: undefined
This is inside: [{"name":"user1","gender":"male"},{"name":"user2"},{"gender":"female"}]


So how can i get and store data into variable at the very beginning?

What I have tried:

JavaScript
var persons;
    function getJSONData() {
        $.getJSON("person.json", function(data){ persons = JSON.stringify(data); 
        console.log("This is inside: "+ persons); });
    }
    getJSONData();
    $(function () {
        console.log("This is outside: " + persons);
    });

I have tried this, but the result is same...
Posted
Updated 13-Feb-18 17:17pm
v2

1 solution

$.getJSON
is asynchronous so you should do:
$.getJSON("person.json", function(json) {
    console.log(json); // this will show the info it in firebug console
});
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900