我试图遍历这个JSON字符串(在一个名为language.json的单独的json文件中),但没有任何工作
{
"language": [
{
"name": "English Languages",
"values": ["English 1", "English 2", "English 3", "English 4"]
},
{
"name": "French Languages",
"values": ["French 1", "French 2", "French 3", "French 4"]
},
{
"name": "Spanish Languages",
"values": ["Spanish 1", "Spanish 2", "Spanish 3", "Spanish 4"]
}
]}
的jQuery
$.getJSON("script/countries.json", function (data) {
$.each(data.language, function (i, v) {
var category = data[i];
console.log(category.name)
$.each(category.values, function (i, v){
console.log(category.values[i])
});
});
有人可以帮我吗?我想打印Lanugage Name,然后打印它的值列表。
输出:
English Language:
English1
English2..
French Language
French1
French2
等等 谢谢!
答案 0 :(得分:1)
假设您的callback
被调用且data
具有所需的值。
data[i]
将返回undefined,因为您正在遍历data.language
,因此您需要使用var category = data.language[i]
或$.each()将当前值作为第二个参数传递给回调。所以你可以
//this will iterate through the data.language list and for each item in the array the callback method will be called.
//The callback method will receive the index of the current item and the item as its 2 parameters
$.each(data.language, function (i, category) {
//here category is the current item in the data.language array so it has the name and values properties
console.log(category.name)
//the same logic follows here, we are iterating through the values array and since it is an array of string calues the second param lang will be the language
$.each(category.values, function (i, lang) {
console.log(lang)
});
});
答案 1 :(得分:0)
这一行:
var category = data[i];
应该是
var category = data.language[i];
答案 2 :(得分:0)
考虑以下代码:
$.getJSON("script/countries.json", function (data) {
$.each(data.language, function (i, v) {
var category = v;//updated
console.log(category.name)
$.each(category.values, function (i, name){
console.log(name);//updated
});
});
});//missing added