0

I want to loop through the JSON I have below with the given JavaScript

{  
    "jsonUrl": "/testUrl",  
    "data": {  
        "country":"US",  
        "company":"ABC",  
        "items":[  
         {  
             "id": "1",  
             "id2": "12345",  
             "total": 1  
         },
         {    
             "id": "2",  
             "id2": "23456",  
             "total": 2  
         }  
      ]  
   }  
}

I've tried the following but I've had no luck.

for (var key in json) {
    if (json.hasOwnProperty(key)) {
         alert(json[key]);
    }
}

When doing this, the alert displays [object][object]. I don't get the actual data inside the object.

jontro
  • 10,241
  • 6
  • 46
  • 71
user123
  • 259
  • 2
  • 6
  • 23
  • `{}` are objects, you access their properties with a dot or with its key. So you could use `json.data.country` or `json['data']['country']`, for example. `[]` are arrays and you can use your method with them without issues. – Alejandro Iván May 11 '17 at 22:47
  • 1
    because alert does toString() on the data... You should not debug with alert(), debug with console.log() – epascarello May 11 '17 at 22:48
  • You also can use the `debugger` keyword and watch contents of the variable in dev tools – Sharikov Vladislav May 11 '17 at 22:59
  • Possible duplicate of [Traverse all the Nodes of a JSON Object Tree with JavaScript](http://stackoverflow.com/questions/722668/traverse-all-the-nodes-of-a-json-object-tree-with-javascript) – jontro May 11 '17 at 23:06

3 Answers3

1

Firstly, don't use alert to watch the contents of the object in this case. When you use alert and you pass object in it, interpreter use toString method on this object. And the result of it is [object Object] construction. You can use JSON.stringify there.

How exactly you parse json? You can do this with JSON.parse.

Also, to not check if object has property with hasOwnProperty method you can use Array.prototype.forEach:

yourArrayData.forEach(function () {
  console.log(JSON.stringify(value));
});

Also you can use for-of (only ES6+):

for (let value of yourArrayData) {
  console.log(JSON.stringify(value));
}
Sharikov Vladislav
  • 7,049
  • 9
  • 50
  • 87
0

A better option is to use the Object.keys() function to get the keys, then iterate to get your info.

Ahmed
  • 23
  • 7
0

The JSON object you are trying to loop through is several levels deep, and therefore you can't simply iterate over the keys and take their values (which in this case are also objects with keys). Depending on what information you want to retrieve, you will have to act differently. If you know the structure in advance, you can iterate over theObject.data.items using a for loop, or if you simply want to get to the the end of the JSON object, you can set up a queue:

let queue = [jsonObject];
while (queue.length > 0) {
    var objectToEvaluate = queue.shift();
    for (var key in objectToEvaluate) {
        if (objectToEvaluate.hasOwnProperty(key)) {
            if (typeof objectToEvaluate[key] === 'object') {
                queue.push(objectToEvaluate[key]);
            }
            else {
                // do something with the objectToEvaluate[key]
            }
        }
    }
}

There are a few things to look out for with a queue. If it's possible for circular references ({a: b, b: a}), then you will need to keep track of which 'nodes' have been checked already. There are also some false positives that go along with checking whether the typeof is an object. I'd suggest reading more up on queues enter link description here

Robert Taussig
  • 581
  • 2
  • 11