如何迭代嵌套的json对象?

时间:2015-09-16 09:23:13

标签: javascript jquery json

我有一个嵌套的JSON对象,我想迭代它。

JSON响应

{
    "specifications": {
        "IP6": {
            "name": "Devices",
            "productSubType": "Device",
            "productSpecificationType": "Phones"
        }
    },
    "offers": {
        "US-PRE-IPHONE-CASE": {
            "path": "productDetails/IP6",
            "familyData": {
                "0": "Missing Family Level data Should be here"
            },
            "facets": [],
            "type": [],
            "offers": {
                "US-PRE-HG-PH-IP6": {
                    "hashDigest": "cf23df2207d99a74fbe169e3eba035e633b65d94",
                    "offerName": "offerNameString",
                    "productName": "iPhone 6 Case Mate Naked Tough Case - Clear",
                    "productOfferings": {
                        "ratings": "4.5",
                        "noOfReviews": "2010"
                    },
                    "offerStatus": {},
                    "displayPriority": "100200",
                    "descriptions": {
                        "shortDescription": "Iphone Decription ",
                        "longDescription": "longDescriptionStri6 descriptionng",
                        "alternativeDescription": "alternativeDescriptionString",
                        "reprsentativeDescription": ""
                    },
                    "specifications": [
                        "someSpecificationId1"
                    ],
                    "brand": "Apple",
                    "productType": "Device",
                    "productSubType": "Phone",
                    "offerType": "",
                    "offerSubType": "",
                    "compatibility": {},
                    "classification": [],
                    "images": {
                        "thumbanail": {
                            "imagePath": "http://s.tmocache.com/images/png/products/accessories/SUPM43270/SUPM43270-small.png"
                        }
                    },
                    "equipmentCharacteristics": {},
                    "offerVariants": {},
                    "type": "hard-good",
                    "offers": [],
                    "family": "IP6",
                    "pricePoints": {
                        "withServicePrice16GBNEW": {
                            "displayPriority": "1001",
                            "pricingMessage": "device price with service activation",
                            "price": "34.99",
                            "discounts": {}
                        }
                    },
                    "dynamicPricingData": {},
                    "inventoryData": {
                        "SKUGOLD16GBN": {
                            "availibility": "Pre-order now!",
                            "availableTimeline": ""
                        }
                    }
                }
            }
        }
    }
}

现在你看到这里有嵌套的JSON对象,我想要

的值
  • 产品名称
  • SHORTDESCRIPTION
  • 的ImagePath
  • 可否订购

我试过的是

function change(){
    var acc = response;  //response is JSON Object mentioned above

    var accArray = [];
    var accArray1 = [];

    for (var obj in acc.specifications){
        accArray.push(obj);
    }    
    alert(accArray[0]);

    for (var obj in accArray[0].offers){
        accArray1.push(obj);
    }

    alert(accArray1[0]);
}

我能够获得第一个警报输出

的第一个对象

IP6

但是当我试图以相同的方式迭代IP6对象时输出是

未定义

我想获取上面提到的所有4个值,然后将它们放在一个数组中。

3 个答案:

答案 0 :(得分:0)

正如Grundy在评论中指出的那样,代码中的objspecifications对象中属性/项的关键。这意味着'obj'只是一个字符串。

要获取对象的引用,请按以下方式更改代码:

for(var obj in acc.specifications){
    accArray.push(acc.specifications[obj]);
}  

为了更好的可读性,请将obj更改为key

答案 1 :(得分:0)

您可以使用 for..in 循环和递归。

function find(obj, fieldName){
    if(Array.isArray(obj)){
        for(var i=0, len=obj.length;i<len;i++){
            var nested = find(obj[i],fieldName);
            if(nested.isFind) return nested;
        }
    }else{
        if(typeof obj !== "object") return {isFind:false};
        for(var i in obj){
            if(i === fieldName) return {isFind:true, value:obj[i]};
            var nested = find(obj[i],fieldName);
            if(nested.isFind) return nested;
        }
    }
    return {isFind:false};
}

此函数返回带有字段isFind的对象,以用于可用值 null 未定义

的情况

&#13;
&#13;
var obj = {
    "specifications": {
        "IP6": {
            "name": "Devices",
            "productSubType": "Device",
            "productSpecificationType": "Phones"
        }
    },
    "offers": {
        "US-PRE-IPHONE-CASE": {
            "path": "productDetails/IP6",
            "familyData": {
                "0": "Missing Family Level data Should be here"
            },
            "facets": [],
            "type": [],
            "offers": {
                "US-PRE-HG-PH-IP6": {
                    "hashDigest": "cf23df2207d99a74fbe169e3eba035e633b65d94",
                    "offerName": "offerNameString",
                    "productName": "iPhone 6 Case Mate Naked Tough Case - Clear",
                    "productOfferings": {
                        "ratings": "4.5",
                        "noOfReviews": "2010"
                    },
                    "offerStatus": {},
                    "displayPriority": "100200",
                    "descriptions": {
                        "shortDescription": "Iphone Decription ",
                        "longDescription": "longDescriptionStri6 descriptionng",
                        "alternativeDescription": "alternativeDescriptionString",
                        "reprsentativeDescription": ""
                    },
                    "specifications": [
                        "someSpecificationId1"
                    ],
                    "brand": "Apple",
                    "productType": "Device",
                    "productSubType": "Phone",
                    "offerType": "",
                    "offerSubType": "",
                    "compatibility": {},
                    "classification": [],
                    "images": {
                        "thumbanail": {
                            "imagePath": "http://s.tmocache.com/images/png/products/accessories/SUPM43270/SUPM43270-small.png"
                        }
                    },
                    "equipmentCharacteristics": {},
                    "offerVariants": {},
                    "type": "hard-good",
                    "offers": [],
                    "family": "IP6",
                    "pricePoints": {
                        "withServicePrice16GBNEW": {
                            "displayPriority": "1001",
                            "pricingMessage": "device price with service activation",
                            "price": "34.99",
                            "discounts": {}
                        }
                    },
                    "dynamicPricingData": {},
                    "inventoryData": {
                        "SKUGOLD16GBN": {
                            "availibility": "Pre-order now!",
                            "availableTimeline": ""
                        }
                    }
                }
            }
        }
    }
}

    function find(obj, fieldName){
        if(Array.isArray(obj)){
            for(var i=0, len=obj.length;i<len;i++){
                var nested = find(obj[i],fieldName);
                if(nested.isFind) return nested;
            }
        }else{
            if(typeof obj !== "object") return {isFind:false};
            for(var i in obj){
                if(i === fieldName) return {isFind:true, value:obj[i]};
                var nested = find(obj[i],fieldName);
                if(nested.isFind) return nested;
            }
        }
        return {isFind:false};
    }

var result = ['productName','shortDescription','imagePath','availibility'].map(function(el){ return find(obj,el).value});

document.getElementById('r').innerHTML = JSON.stringify(result,null,2);
&#13;
<pre id='r'></pre>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您的json代码是一种复杂的数据绑定结构。它与c#复杂数据绑定相同。所以你需要通过它调用名称来调用obj。

例如:

var data = {"ex":{"a":{"a1":"a1","a2":"a2"},"b":{"b1":"b1","b2":"b2"}}}

所以数据是一个类,它包括&#34; ex&#34;宾语 data returns =&gt; Object {ex:Object}

如果您需要访问&#34; a&#34;或&#34; b&#34;对象意味着,您需要通过&#34; ex&#34;对象

例如:

data.ex.a =&gt;对象{a1:&#34; a1&#34;,a2:&#34; a2&#34;}

代码

 for(var obj in acc.specifications){
        accArray.push(obj);
}  

obj只推送acc.sppectification对象的第一个元素。

所以请试试这个。

foreach(var obj acc.specification){
     arr1.push(acc.specification[obj])
}

foreach (var obj acc.offers){
   arr2.push(acc.offers[obj])
}
相关问题