[英]How to iterate nested json object?
I have a nested JSON Object and i want to iterate that. 我有一个嵌套的JSON对象,我想对其进行迭代。
JSON Response 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": ""
}
}
}
}
}
}
}
Now as you see there are nested JSON objects in this and I want the value of 现在,如您所见,其中有嵌套的JSON对象,我想要的值是
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 IP6
but when I am trying to iterarte the IP6 object in same way the output is 但是当我尝试以相同的方式遍历IP6对象时,输出为
undefined 未定义
I want to fetch all the 4 values as I mentioned above and then put them in an array. 我想如上所述提取所有4个值,然后将它们放入数组中。
As Grundy pointed out in his comment, obj
in your code is the key of properties/items in specifications
object. 正如Grundy在他的评论中指出的那样,代码中的
obj
是specifications
对象中属性/项的关键。 That means 'obj' is just a string. 这意味着“ obj”只是一个字符串。
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
为了提高可读性,
obj
更改为key
You can use for..in loop and recursion. 您可以使用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};
}
this function return object with field isFind
for case when available value can be null or undefined 如果可用值可以为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>
Your json code is a complex data binding structure. 您的json代码是一个复杂的数据绑定结构。 It same like c# complex data binding.
就像c#复杂数据绑定一样。 So you need to call the obj by through it call name.
因此,您需要通过其调用名称来调用obj。
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} 所以数据是一个类,它包含“ ex”对象数据,返回=> Object {ex:Object}
if you need to access "a" or "b" object means , you need to access through the"ex" object. 如果您需要访问“ a”或“ b”对象,则需要通过“ ex”对象进行访问。
for eg: 例如:
data.ex.a => Object {a1: "a1", a2: "a2"} data.ex.a =>对象{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. obj仅推送acc.sppectification对象的第一个元素。
So please try this. 所以请尝试这个。
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.