Reputation: 65
I have the following JSON file:
{
"Alaska": [{
"countryName":"Alaska",
"Phone”:”123”,
"Rate”:”2¢/min"
}],
"Argentina": [{
"countryName":"Argentina",
"Phone”:”456”,
"Rate”:”4¢/min"
}],
"Australia": [{
"countryName":"Australia",
"Phone”:”789”,
"Rate”:”6¢/min
}]
}
And I'm loading it and storing it in a variable like so:
var jsonOutput = {};
$.ajax({
url: “countries.json",
dataType: 'json',
success: function(data) {
jsonOutput = data;
}
});
How can I iterate over it, using jQuery's .each
similar to this?:
$(jsonOutput).each(function() {
var output = this.countryName + this.Phone + this.Rate;
console.log(output);
});
I have searched through tons of examples here but I couldn't find anything quite like this - most have all the arrays inside a parent object, and use the object.key
format to read the data, but in my case it's returning 'undefined'.
Upvotes: 1
Views: 52
Reputation: 33618
It should be something like below
$.each(jsonOutput, function(key, value) {
var output = key + value[0].Phone + value[0].Rate;
console.log(output);
});
var jsonOutput = JSON.parse('{\
"Alaska": [{\
"countryName":"Alaska",\
"Phone":"123",\
"Rate":"2¢/min"\
}],\
\
"Argentina": [{\
"countryName":"Argentina",\
"Phone":"456",\
"Rate":"4¢/min"\
}],\
\
"Australia": [{\
"countryName":"Australia",\
"Phone":"789",\
"Rate":"6¢/min"\
}]\
}');
$.each(jsonOutput, function(key, value) {
var output = key + value[0].Phone + value[0].Rate;
console.log(output);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 1