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.

4
  • {} 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. Commented May 11, 2017 at 22:47
  • 1
    because alert does toString() on the data... You should not debug with alert(), debug with console.log() Commented May 11, 2017 at 22:48
  • You also can use the debugger keyword and watch contents of the variable in dev tools Commented May 11, 2017 at 22:59
  • Possible duplicate of Traverse all the Nodes of a JSON Object Tree with JavaScript Commented May 11, 2017 at 23:06

3 Answers 3

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));
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

And check the type with the typeof operator.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.