7

I'm just starting to use javascript and json.

I need to read data (getInformation function) from a json file when processing an event in a javascript function. So I need it to be synchronic. I don't know if I am missing something in the code, or if I have to create an Request and handle the callback, or if I need to import additional javascript to use json. Because I don't know how to make it work. It doesn't work because at the end the array is empty. Any help is aprreciated.

The json file:

{"Users": [
    {"Name": "Jane",
        "Points": 67,
        "age": 23},
    {
        "Name": "Sam",
        "Points": 65,
        "age": 21}
]} 

Option 1 - Function called by another function which is processing an event:

var getInformation = function() 
{
    var path = "./data/users.json";
    var informationArray= [];
    console.log("Loading ....");
    $.getJSON(path, function(data) 
    {
        $.each(data, function(key, val) 
        {
            informationArray.push(key + '-' + val);
        });
    }); 
    return informationArray; 
}

Option 2 - Function called by another function which is processing an event:

var getInformation = function() { 
var path = "./data/users.json";
var informationArray= [];
$.ajax({
         url: path,
         async: false,
         dataType: 'json',
         success: function(response) {
         $.each(response.items,
         function(item) {
         informationArray.push(item);
         });
         informationArray.push("success");
         }
         }); 
   return informationArray; }

I have seen the following thread and tried what is there but doens't work for me. I would like to know where is the problem in my code or if require any special configuration.

Thread: Is there a version of $getJSON that doesn't use a call back?

Community
  • 1
  • 1
user2333683
  • 71
  • 1
  • 1
  • 3
  • what is the question? what isn't working? – Evan Davis Apr 29 '13 at 21:20
  • When you say you are trying to parse a local file, do you mean on the client or server? If it's on the server, you need to use the URL to the file instead of a path. – Justin Apr 29 '13 at 21:22
  • Is the JSON being dynamically generated, or is it coming from a `.json` file? Because JSON is simply JavaScript, it can also be loaded in the same way a script is, and stored in local memory for interaction. Just a thought. – oomlaut Apr 29 '13 at 21:28
  • The question is where are the mistakes, because the array in which I intend to include the data of the json file is empty at the end of the function. I mean parse or access to the elements of the json file. It is not dynamic, is fixed information. The local json file in the server yes, how should I specify the url? Nice, how can I load a script to store it dynamically, it doesn't causes efficiency problems? – user2333683 Apr 29 '13 at 21:30
  • I don't really see why the request would need to be synchronous. Server communication always should be async. – Bergi Apr 29 '13 at 21:44
  • The problem is that your path needs to be a URL, you calling `./data/users.json` is not going to work. It needs to be something like `http://yoursite.com/data/users.json` – Justin Apr 29 '13 at 21:52

2 Answers2

7

When JavaScript is running in a browser it needs to make an AJAX request to the server to access a JSON file. It is possible to write the AJAX request by hand but that is complex and difficult to make work in all browsers. Instead most people use a library like jQuery. You will need to include jQuery in your web page with something like:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>

Then in any script tag lower in the html page you should be able to do something like:

$.ajax({
  url: "data/users.json",
  dataType: "json",
  success: function(response) {
    $.each(response.Users, function(item) {
      informationArray.push(item);
    });
    informationArray.push("success");
  }
});

see http://api.jquery.com/jQuery.ajax/

olleicua
  • 2,039
  • 2
  • 21
  • 33
  • I'm using - //ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js - jquery-ui-1.8.17.custom.min.js Changing to 1.9.1/ dissable the rest funcions. Could this be the cause of having the array empty? Thanks. – user2333683 Apr 29 '13 at 22:10
  • Unlikely. It might be that you are getting an empty array because your JSON object has no 'items' property. It looks like you want the 'Users' property. – olleicua Apr 30 '13 at 23:40
0

To load a JSON file (and not require a callback) you'd use:

var url = 'http://yoursite.com/data/users.json';
var j = [];
$.ajax({
  type: 'GET',
  url: url,
  dataType: 'json',
  success: function(data) { j = data;},
  async: false
});

alert(j.Users[0].Name);
Justin
  • 26,443
  • 16
  • 111
  • 128
  • Thanks. I'm getting now this error. Uncaught TypeError: Cannot read property '0' of undefined. By the way, is there a way to set the url dynamically? – user2333683 Apr 29 '13 at 21:54
  • 1
    It is not working, the j array is empty. Do I need to configure some additional library or something? – user2333683 Apr 29 '13 at 22:02
  • Yes, you can set the URL dynamically, you'd just make it a var like in your 'option 2' above. What URL are you using? If you enter it in a browser, the JSON should display. – Justin Apr 29 '13 at 22:04
  • As I'm testing in the workstation and I'm using Netbeans the URL i wrote is http://localhost:8383/Project/data/users.json – user2333683 Apr 29 '13 at 22:12
  • Does that URL load the JSON file when you put it in firefox or whatever browser you use? – Justin Apr 29 '13 at 22:13
  • I would add `alert(data)` or `console.log(data)` inside the success function and make sure the JSON is getting pulled in there. If not, you could try changing your URL to '/Project/data/users.json' and see if that helps? – Justin Apr 29 '13 at 23:05
  • Hummm, by doing the change of the url to '/Project/data/users.json' doesn't make any difference, the access to the first object of the array is stil undefined. The problem is locating the URL, I guess I need to configure something else. But I don't know what it is. I used the URL of your dropbox of the example working and it doesn't seem to recognize it neither. – user2333683 Apr 30 '13 at 05:30
  • You should create a jsfiddle.net showing what's not working. If it works there you're going to have to start working from a web server instead of working locally. – Justin Apr 30 '13 at 18:10
  • @user2333683 make sure you're using async:false. – prm296 Feb 23 '19 at 21:44