2010-11-05 14 views
5

un servicio web devuelve el siguiente objeto JSON anidada:impresión anidada JSON sin usar nombres de variables

{"age":"21-24","gender":"Male","location":"San Francisco, CA","influencer score":"70-79","interests":{"Entertainment":{"Celebrities":{"Megan Fox":{},"Michael Jackson":{}},},"Social Networks & Online Communities":{"Web Personalization": {},"Journals & Personal Sites": {},},"Sports":{"Basketball":{}},},"education":"Completed Graduate School","occupation":"Professional/Technical","children":"No","household_income":"75k-100k","marital_status":"Single","home_owner_status":"Rent"} 

sólo quiero iterar a través de este objeto sin especificar el nombre de propiedad, he intentado el siguiente código:

for (var data in json_data) { 
    alert("Key:" + data + " Values:" + json_data[data]); 
} 

sin embargo, imprime el valor como [object Object] si es un valor anidado, ¿hay alguna manera de seguir iterando en valores anidados?

Respuesta

6

Prueba esto:

function iter(obj) { 
    for (var key in obj) { 
    if (typeof(obj[key]) == 'object') { 
     iter(obj[key]); 
    } else { 
     alert("Key: " + key + " Values: " + obj[key]); 
    } 
    } 
} 

BB: + añadido para evitar errores.

+0

typeof (someObject) devuelve "object" no "Object" ... Observe la "o" minúscula –

+0

Good catch. :) ¡Gracias! –

3

Puede hacerlo de forma recursiva.

function alertobjectKeys(data) { 
    for (var key in data) { 
    if (typeof(data[key]) == "object" && data[key] != null) { 
     alertobjectKeys(data[key]); 
    } else { 
     alert("Key:" + key + " Values:" + data[key]); 
    } 
    } 
} 
+0

Dentro de su llamada anidada necesita datos [clave]; de lo contrario, simplemente reitera el mismo objeto que recibió. –

+0

@ g.d.d.c ... gracias ... Lo arreglé –

0

Siempre se puede crear una función recursiva:

function alertObj(obj) { 
    for (var data in obj) { 
     if(typeof(obj[data]) === "object") 
      alertObj(obj[data]); 
     else 
      alert("Key:" + data + " Values:" + obj[data]); 
    } 
} 

Mientras usted no se preocupa de manera recursiva demasiado (lo que probablemente no es necesario con objetos JSON).

También puede hacer esto con una estructura de cola o pila (matriz):

function alertObj_queue(obj) { // Breadth-first 
    var arrPrint = [{key:"Object", data:obj}]; // Initialize array with original object 

    for(var i = 0; i < arrPrint.length; i++) { 
     if(typeof(arrPrint[i].data) === "object") { 
      for(var k in arrPrint[i].data) { // Add each to end of array 
       arrPrint.push({key: k, data: arrPrint[i].data[k]}); 
      } 
      alert("Object key: " + arrPrint[i].key); 
     } else { 
      alert("Key:" + arrPrint[i].key + " Values:" + arrPrint[i].data); 
     } 
    } 
} 

function alertObj_stack(obj) { // Depth-first 
    var arrPrint = [{key:"Object", data:obj}]; // Initialize array with original object 

    while(arrPrint.length) { 
     var o = arrPrint.pop(); 
     if(typeof(o.data) === "object") { 
      for(var k in o.data) { // Add each to end of array 
       arrPrint.push({key: k, data: o.data[k]}); 
      } 
      alert("Object key: " + o.key); 
     } else { 
      alert("Key:" + o.key + " Values:" + o.data); 
     }  
    } 
} 
+0

su código no es correcto. Usted pasa obj pero usa json_data en su bucle for .... json_data no está definido. –

+0

desafortunadamente ambos no funcionan, solo pasan por el 1er nivel –

+0

@HeoQue: solo ve alertas en el primer nivel porque en sus datos, todo debajo del primer nivel es un objeto, por lo que el ciclo mirará "Deportes" y ver que es un objeto, luego bajar a "Baloncesto" y ver que también es un objeto, por lo que no 'alerta' para ninguno de esos. Probablemente sea más fácil tener algunos de sus datos JSON como matrices ("Deportes", "Celebridades", etc.). – palswim

0

Por supuesto, esto requiere la repetición

(function(obj) { 
    for (var key in obj) if (obj.hasOwnProperty(key)) { 
    if (typeof obj[key] == 'object' && obj[key] !== null) 
     arguments.callee(obj[key]); 
    else 
     alert("Key: " + key + " Values: " + obj[key]); 
    } 
)(json_data)); 
+0

** No requiere ** recursividad, pero la recursividad puede ayudar si sus datos no son ridículamente grandes. – palswim

0
function recursiveParse(variable) { 
    for (var key in variable) { 
     if ((is_object(variable[key])) || (is_array(variable[key]))) { 
      recursiveParse(variable[key]); 
     } else { 
      // Process variable here 
     } 
    } 
} 

A continuación, sólo llamar a esa función con ser el parámetro los datos json, analizará los objetos restantes y las matrices recursivamente.

+0

donde están las definiciones para is_object() e is_array()? –

+0

En otra biblioteca me olvidé de contarte pero estoy tan acostumbrado que olvidé que no era javascript básico. Me disculpo. –

0

Supongo que en su solicitud (suponiendo que sea Ajax) no está especificando el tipo de datos que se devolverá como 'json'.

Cuestiones relacionadas