Elliot
Elliot

Reputation: 13835

Return array from JSON file with JQuery?

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

Upvotes: 0

Views: 9111

Answers (5)

bfavaretto
bfavaretto

Reputation: 71918

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.
    });
}

Upvotes: 0

loganfsmyth
loganfsmyth

Reputation: 161457

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.

Upvotes: 2

Milindu Sanoj Kumarage
Milindu Sanoj Kumarage

Reputation: 2774

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.

Upvotes: 0

Brad Harris
Brad Harris

Reputation: 1520

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);
}

Upvotes: 1

Boris Bachovski
Boris Bachovski

Reputation: 662

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);
});

Upvotes: 0

Related Questions