我有这个JSON:
{
"solution": {
"section1": {
"cell-1": "1",
"cell-2": "2",
"cell-3": "3",
"cell-4": "4",
"cell-5": "5",
"cell-6": "6",
"cell-7": "7",
"cell-8": "8",
"cell-9": "9"
},
"section2": {
"cell-1": "1",
"cell-2": "2",
"cell-3": "3",
"cell-4": "4",
"cell-5": "5",
"cell-6": "6",
"cell-7": "7",
"cell-8": "8",
"cell-9": "9"
}
}
}
我的代码:
$.getJSON('/static/front/js/src/sudoku/22122016.json', function(data) {
$.each(data.solution.section1[0], function() {
$.each(this, function(cell, cellNumber) {
console.log(cell + ' ' + cellNumber);
});
});
});
此代码给出了以下错误:
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in 1
at isArrayLike (jquery.js:535)
at Function.each (jquery.js:362)
at String.<anonymous> (main.js:61)
at Function.each (jquery.js:371)
at Object.success (main.js:60)
at fire (jquery.js:3187)
at Object.fireWith [as resolveWith] (jquery.js:3317)
at done (jquery.js:8757)
at XMLHttpRequest.<anonymous> (jquery.js:9123)
in jquery.js:535
我需要单独访问每个部分,因此我需要进入每个部分,然后遍历每个部分并获取其值。我怎样才能做到这一点?
答案 0 :(得分:3)
你可以迭代细胞:
$.each(data.solution.section1, function(cell, cellNumber) {
console.log(cell + ' ' + cellNumber)
})
答案 1 :(得分:2)
没有测试,我猜:
$.getJSON('/static/front/js/src/sudoku/22122016.json', function(data) {
$.each(data.solution, function(sectionName, cells) {
$.each(cells, function(cellName, cellNumber) {
console.log(cellName + ' ' + cellNumber);
});
});
});
您可能想要考虑通过将其拆分为方法或直接导航到单元格来降低此时的缩进级别。
答案 2 :(得分:1)
我不确切知道你想要得到什么,但是将“[0]”放在data.solution.section1的末尾会阻止对data.solution.section1内容的索引。
答案 3 :(得分:1)
这是一般的方法:
for (var key in a.solution.section1) {
if (a.solution.section1.hasOwnProperty(key)) {
console.log(key + " -> " + a.solution.section1[key]);
}
}