-1

I've been trying to convert a word list stored in a JSON file into an array in my code. This is my code so far:

     var jstring;

    $.getJSON( "link_to_json.json", function( json ) {
     jstring= JSON.parse(json);
 });
    
  console.log(jstring[0]); 

The console log says that the object is undefined no matter what I change.

Bob Bob
  • 28
  • 5
  • 3
    getJSON is asynchronous. The way you have it in your code the console.log call is going to run before your JSON.parse call. – ray Feb 27 '21 at 17:37
  • @rayhatfield How do I change it so that the console.log runs after? – Bob Bob Feb 27 '21 at 17:39

1 Answers1

0

You should try one of these approaches.

var JSONItems = []; 
$.getJSON( "js/settings.json", function( data){ 
  JSONItems = data; 
  console.log(JSONItems); 
}); 

or

var JSONItems = []; 
$.get( "js/settings.json", function( data){ 
  JSONItems = JSON.parse(data); 
  console.log(JSONItems); 
}); 
Mr.UV
  • 100
  • 1
  • 7