0

I have a JSON file that contains the following: [{name:joe,number:4},{name:ralph,number:76}]

Simply put, I'm trying to create a function that returns that as an array:

function createArray(){
    x = $.getJSON("/names.json", function(json) {
        var myArray = [];
        $.each(json, function() {   
            myArray.push(json);
        });
        return myArray;
    });
    return x;
}

This is not working, I'm not sure what part of it doesnt make sense

5
  • Have you tried debugging? If you add an alert(json); before the var myArray ... , does it tell you it's an object? Or is there an error server side perhaps? Commented Mar 30, 2012 at 3:35
  • does it even return anything? Commented Mar 30, 2012 at 3:35
  • It says its returning an object, and the array is in the "responseText" Commented Mar 30, 2012 at 3:37
  • check it using the console. do a console.log(json) in the callback Commented Mar 30, 2012 at 3:38
  • in the console log, the object just contains the names and numbers Commented Mar 30, 2012 at 3:40

5 Answers 5

2

You are doing an asynchronous request. $.getJSON does not return the result of your callback.

You need to pass a callback into your createArray function. Also, if your JSON data is already an array, you don't need to process the response data.

function createArray(cb){
  $.getJSON("/names.json", cb);
}

So for example you'd change this:

var myArray = createArray();
// Process myArray

into this:

createArray(function(myArray) {
  // Process myArray
});

The problem is that you can't just assign the result of a network request. When you call getJSON, you start a network request, but after the request starts, the JS will keep running other stuff. The get the result of an asynchronous request, you need to use a callback that will process that data and do something with it.

Sign up to request clarification or add additional context in comments.

4 Comments

I'm not sure I understand... How do I call the function then to get the array? I have nothing to put in the callback..
Any logic you have that uses that data would be put into the callback function. If you give a bit of context of how you are calling this, I can give an example.
I just want to create a variable in a different function that has the array.. i.e. var myArray = createArray();
@Elliot I added a bit more explanation.
1

Like loganfsmyth said, you're not taking into account that $.getJSON is asynchronous, and it's not going to return what you think it is (it actually returns a jqXHR Object. Write your code to handle the asynchronous nature using closures:

function createArray(cb){
    $.getJSON("/names.json", function(json) {
        var myArray = [];
        $.each(json, function() {   
            myArray.push(json);
        });
        cb(myArray);
    });
}

createArray(function(array) {
    //your array is available here
    console.log(array);
}

Comments

0

Your keys and values should be Strings

[{"name":"joe", "number":4},{"name":"ralph", "number":76}]

and this

$.each(json, function() {   
     myArray.push(json);
});

should become

$.each(json, function(key, val) {
      if(myArray[key] == undefined)
      {     myArray[key] = new Array();
      }
      myArray[key].push(val);
});

2 Comments

I want the array to be the same as in the JSON file though, shouldn't I need both the key and the val?
THen you are looking at Javascript two dimensional arrays
0

What you get from 'json' is an array. try this,

var ar = [{
    "name": "joe",
    "number": "4"},
{
    "name": "ralph",
    "number": "76" }];


alert(ar[0].name);​

This would alert the name "joe". ar[0] is the first element of the array and in your case this is an object with properties name and number. You can get/set them in normal way.

    var myArray = [];
    $.getJSON("/names.json", function(json) {

            myarray=json;
    });

NowmyArray is an array with your Objects.

Comments

0

You can't do that, your function will return a promise object, but never the json response itself. The response will be available from the promise only after the request is complete (which is not immediately after function return because the request is asynchronous).

Why don't you just use the json from the callback? I mean this:

function createArray(){
    $.getJSON("/names.json", function(json) {
        // Whatever you need to do with your json,
        // do it here. This code will run after  
        // createArray returns. And you can't
        // return anything from here, it's useless.
        // Actually, you don't even need the outer
        // createArray function.
    });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.