简体   繁体   English

使用javascript / jQuery遍历JSON结构

[英]Loop through JSON structure using javascript/jQuery

I want to loop through the JSON I have below with the given JavaScript 我想使用给定的JavaScript遍历下面的JSON

{  
    "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] . 这样做时,警报显示[object][object] I don't get the actual data inside the object. 我没有在对象内部获得实际数据。

Firstly, don't use alert to watch the contents of the object in this case. 首先,在这种情况下,不要使用alert监视对象的内容。 When you use alert and you pass object in it, interpreter use toString method on this object. 当您使用alert并在其中传递对象时,解释器在此对象上使用toString方法。 And the result of it is [object Object] construction. 结果是[object Object]构造。 You can use JSON.stringify there. 您可以在JSON.stringify使用JSON.stringify

How exactly you parse json? 您究竟如何解析json? You can do this with JSON.parse . 您可以使用JSON.parse做到这一点。

Also, to not check if object has property with hasOwnProperty method you can use Array.prototype.forEach : 另外, hasOwnProperty检查对象是否具有具有hasOwnProperty方法的属性,可以使用Array.prototype.forEach

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

Also you can use for-of (only ES6+): 您也可以使用for-of (仅适用于ES6 +):

for (let value of yourArrayData) {
  console.log(JSON.stringify(value));
}

更好的选择是使用Object.keys()函数获取密钥,然后进行迭代以获取您的信息。

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). 您尝试循环通过的JSON对象有多个层次,因此您不能简单地遍历键并获取它们的值(在这种情况下,也就是带有键的对象)。 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: 如果您事先知道结构,则可以使用for循环遍历theObject.data.items,或者如果您只想到达JSON对象的末尾,则可以设置一个队列:

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. 如果有可能使用循环引用({a:b,b:a}),那么您将需要跟踪已经检查了哪些“节点”。 There are also some false positives that go along with checking whether the typeof is an object. 检查typeof是否是对象还伴随着一些误报。 I'd suggest reading more up on queues enter link description here 我建议阅读更多关于队列的信息,在此处输入链接描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM