我有以下JSON文件:
{
"Alaska": [{
"countryName":"Alaska",
"Phone”:”123”,
"Rate”:”2¢/min"
}],
"Argentina": [{
"countryName":"Argentina",
"Phone”:”456”,
"Rate”:”4¢/min"
}],
"Australia": [{
"countryName":"Australia",
"Phone”:”789”,
"Rate”:”6¢/min
}]
}
我正在加载它并将其存储在一个变量中:
var jsonOutput = {};
$.ajax({
url: “countries.json",
dataType: 'json',
success: function(data) {
jsonOutput = data;
}
});
如何使用与此类似的jQuery .each
迭代它?:
$(jsonOutput).each(function() {
var output = this.countryName + this.Phone + this.Rate;
console.log(output);
});
我在这里搜索了大量的例子,但我找不到任何类似的东西 - 大多数都有父对象内的所有数组,并使用object.key
格式来读取数据,但在我的情况下它正在返回'未定义'。
答案 0 :(得分:1)
应该是下面的内容
$.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>