简体   繁体   中英

How to iterate nested json object?

I have a nested JSON Object and i want to iterate that.

JSON Response

{
    "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": ""
                        }
                    }
                }
            }
        }
    }
}

Now as you see there are nested JSON objects in this and I want the value of

  • productName
  • shortDescription
  • imagePath
  • availibility

What I have tried is

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

I am able to get the first object the first alert output is

IP6

but when I am trying to iterarte the IP6 object in same way the output is

undefined

I want to fetch all the 4 values as I mentioned above and then put them in an array.

As Grundy pointed out in his comment, obj in your code is the key of properties/items in specifications object. That means 'obj' is just a string.

To get reference to the object, change your code as below:

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

For better readability change obj to key

You can use for..in loop and recursion.

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};
}

this function return object with field isFind for case when available value can be null or undefined

 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> 

Your json code is a complex data binding structure. It same like c# complex data binding. So you need to call the obj by through it call name.

for eg:

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

so data is a class and it includes "ex" object data returns =>Object {ex: Object}

if you need to access "a" or "b" object means , you need to access through the"ex" object.

for eg:

data.ex.a => Object {a1: "a1", a2: "a2"}

in your code

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

obj only push 1st element of acc.sppectification object.

So please try this.

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

foreach (var obj acc.offers){
   arr2.push(acc.offers[obj])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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