erol_smsr
erol_smsr

Reputation: 1496

Can't parse JSON file with jQuery

I have this 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"
        }
    }
}

My code:

$.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);
        });
    });
});

This code gives me the following error:

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

I need to access each section separately, so I need to go into each section and then iterate through each key and get its value. How can I achieve this?

Upvotes: 0

Views: 307

Answers (4)

mikey
mikey

Reputation: 171

Without testing it, I would guess:

$.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);
        });
    });
});

You might want to think about decreasing the indentation level at this point by splitting it up into methods or navigating to the cells directly.

Upvotes: 2

maximast
maximast

Reputation: 118

This is the general way to go:

for (var key in a.solution.section1) {
  if (a.solution.section1.hasOwnProperty(key)) {
    console.log(key + " -> " + a.solution.section1[key]);
  }
}

Upvotes: 1

longestwayround
longestwayround

Reputation: 1019

I don't know exactly what you are trying to get, but putting the "[0]" at the end of data.solution.section1 prevents the indexing across the contents of data.solution.section1.

Upvotes: 1

unkmas
unkmas

Reputation: 987

You can just iterate over cells:

$.each(data.solution.section1, function(cell, cellNumber) {
  console.log(cell + ' ' + cellNumber) 
})

Upvotes: 3

Related Questions