Reputation: 25
What is the best way to create javascript array from json file? I have four empty JavaScript array that I would like to populate with data imported from a json file.
var firstname = new Array();
var address= new Array();
var city = new Array();
File Json : "file.json"
[
{"name ": "John", "address": "350 Fifth Avenue", "city ": "New York"},
{"name ": "Mark", "address": "1101 Arch St", "city ": "Philadelphia"},
{"name ": "Jack", "address": "60th Street", "city ": "Chicago"}
]
I try:
$.getJSON('file.json',function (data) {
for (var i = 0; i < data.length; i++) {
firstname.push.apply( firstname, data[i].firstname );
address.push.apply( address, data[i].address );
city.push.apply( city, data[i].city );
}
});
but arrays are still empty. Thanks in advance
================================ SOLVED ===============================
$.ajax({
async: false,
url: 'file.json',
data: "",
accepts:'application/json',
dataType: 'json',
success: function (data) {
for (var i = 0; i < data.length; i++) {
firstname.push( data[i].firstname );
address.push( data[i].address );
city.push( data[i].city );
}
}
})
// Get arrays outside callback function
console.log('result: '+firstname.length); // result: 3
Upvotes: 1
Views: 9041
Reputation: 318182
You seem to have the order wrong, data
is the array so it's not
data.name[i]
but
data[i].name
and removing the strange apply
it would be
$.getJSON('json.js',function (data) {
for (var i = 0; i < data.length; i++) {
name.push( data[i].name );
address.push( data[i].address );
city.push( data[i].city );
}
});
Also note that name
is a bad choice for a variable name in the global context.
Upvotes: 5
Reputation: 943537
You have two or three problems.
Remove the quotes from around the outside of it.
Seriously consider giving is a .json
file extension, then you are more likely to get the right MIME type for JSON. (JSON data files are not JavaScript programs).
File Json : "data.json"
[
{"name ": "John", "address": "350 Fifth Avenue", "city ": "New York"},
{"name ": "Mark", "address": "1101 Arch St", "city ": "Philadelphia"},
{"name ": "Jack", "address": "60th Street", "city ": "Chicago"}
]
This is overly complicated and is accessing properties in the wrong order.
name.push.apply(name, data.name[i]);
Forget about using apply
. You don't need it.
Then note that your JSON array contains the objects, not the other way around. You need to access the array index before the property name:
name.push(data[i].name);
Finally - your code doesn't show how you are testing the result. Remember that Ajax is asynchronous, so that if you examine the values of your arrays outside the callback function, they might not have been populated yet.
Upvotes: 1