Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading local JSON file

I'm trying to load a local JSON file but it won't work. Here is my JavaScript code (using jQuery):

var json = $.getJSON("test.json"); var data = eval("(" +json.responseText + ")"); document.write(data["a"]); 

The test.json file:

{"a" : "b", "c" : "d"} 

Nothing is displayed and Firebug tells me that data is undefined. In Firebug I can see json.responseText and it is good and valid, but it's strange when I copy the line:

 var data = eval("(" +json.responseText + ")"); 

in Firebug's console, it works and I can access data.

Does anyone have a solution?

like image 678
Patrick Browne Avatar asked Sep 08 '11 10:09

Patrick Browne


People also ask

How do I run a local JSON file?

Use the require() Function to Load JSON Files in JavaScript In JavaScript, we can use the require() method to load files and modules. This takes the path of the local file where it has been saved. With the help of the console. log() function, it loads the data in the server and displays it.


1 Answers

$.getJSON is asynchronous so you should do:

$.getJSON("test.json", function(json) {     console.log(json); // this will show the info it in firebug console }); 
like image 160
seppo0010 Avatar answered Sep 27 '22 21:09

seppo0010