繁体   English   中英

如何迭代嵌套的json对象?

[英]How to iterate nested json object?

我有一个嵌套的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对象,我想要的值是

  • 产品名称
  • 简短的介绍
  • 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个值,然后将它们放入数组中。

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

要获取对该对象的引用,请如下更改代码:

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

为了提高可读性, obj更改为key

您可以使用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};
}

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

 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); 
 <pre id='r'></pre> 

您的json代码是一个复杂的数据绑定结构。 就像c#复杂数据绑定一样。 因此,您需要通过其调用名称来调用obj。

例如:

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

所以数据是一个类,它包含“ ex”对象数据,返回=> Object {ex:Object}

如果您需要访问“ a”或“ b”对象,则需要通过“ ex”对象进行访问。

例如:

data.ex.a =>对象{a1:“ a1”,a2:“ a2”}

在你的代码中

 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])
}

暂无
暂无

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

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