[英]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對象,我想要的值是
我試過的是
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在他的評論中指出的那樣,代碼中的obj
是specifications
對象中屬性/項的關鍵。 這意味着“ 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.