2011-07-29 15 views
13

Tengo un problema al manejar los datos JSON dentro de JavaScript, específicamente en lo que respecta al uso de los datos como una matriz y el acceso e iteración a través de valores individuales. El archivo JSON está estructurado de la siguiente manera:JSON to javaScript array

{ 
    "head": { 
    "vars": [ "place" , "lat" , "long" , "page" ] 
    } , 
    "results": { 
    "bindings": [ 
     { 
     "place": { "type": "literal" , "value": "Building A" } , 
     "lat": { "datatype": "http://www.w3.org/2001/XMLSchema#float" , "type": "typed-literal" , "value": "10.3456" } , 
     "long": { "datatype": "http://www.w3.org/2001/XMLSchema#float" , "type": "typed-literal" , "value": "-1.2345" } , 
     "page": { "type": "uri" , "value": "http://www.example.com/a.html" } 
     } , 
     { 
     "place": { "type": "literal" , "value": "Building B" } , 
     "lat": { "datatype": "http://www.w3.org/2001/XMLSchema#float" , "type": "typed-literal" , "value": "11.3456" } , 
     "long": { "datatype": "http://www.w3.org/2001/XMLSchema#float" , "type": "typed-literal" , "value": "-2.2345" } , 
     "page": { "type": "uri" , "value": "http://www.example.com/b.html" } 
     } , 
     { 
     "place": { "type": "literal" , "value": "Building C" } , 
     "lat": { "datatype": "http://www.w3.org/2001/XMLSchema#float" , "type": "typed-literal" , "value": "12.3456" } , 
     "long": { "datatype": "http://www.w3.org/2001/XMLSchema#float" , "type": "typed-literal" , "value": "-3.2345" } , 
     "page": { "type": "uri" , "value": "http://www.example.com/c.html" } 
     } 
    ] 
    } 
} 

Quiero ser capaz de convertir esto en una matriz de JavaScript de la siguiente manera con el fin de que puedo iterar a través de él y sacar los valores para cada lugar en orden:

var locations = [ 
     ['Building A',10.3456,-1.2345,'http://www.example.com/a.html'], 
     ['Building B',11.3456,-2.2345,'http://www.example.com/b.html'], 
     ['Building C',12.3456,-3.2345,'http://www.example.com/c.html'] 
]; 

¿Alguien tiene algún consejo sobre cómo lograr esto? He intentado el siguiente, pero recoge el "tipo" dentro del JSON, en lugar de sólo el valor:

$.each(JSONObject.results.bindings, function(i, object) { 
    $.each(object, function(property, object) { 
     $.each(object, function(property, value) { 
       value; 
     }); 
    }); 
}); 

Cualquier ayuda, sugerencias, consejos o correcciones sería muy apreciada.

Respuesta

29
var locations = []; 
$.each(JSONObject.results.bindings, function(i, obj) { 
    locations.push([obj.place.value, obj.lat.value, obj.long.value, obj.page.value]); 
}); 

iterar a través de bindings, y poner las propiedades place.value, lat.value, long.value y page.value de cada elemento en una matriz, a continuación, añadir esta matriz a locations.

Su código actual usa object dos veces, así como property, sobrescribiendo esas variables. Debe usar nombres de variable únicos en bucles anidados para poder distinguirlos.

+0

Ahhh ... tan simple muchas gracias –

+0

tantos se olvide de ver nuestra empuje (er) cuando necesitar un arreglo –

0

se puede hacer algo como esto

for (i=0;i<JSONObject.results.bindings.length;i++) 

{newObject = JSONObject.results.bindings; 
somethingelse = newObject[i].place.type; 

} 
5

de Javascript puro muy similar a la respuesta aceptada (que me gusta)

me gusta usar una negativa, mientras que bucle de velocidad (más de un tradicional for loop) cuando tengo una longitud definida. Esto es probablemente más rápido que la respuesta jQuery también.

var i = JSONObject.results.bindings.length; 
var locations = []; 
while (i--) { 
    t = JSONObject.results.bindings[i]; 
    locations.push([t.place.value, t.lat.value, t.long.value, t.page.value]); 
}; 
//now show the places 
var c = locations.length; 
while (c--) { 
    alert(locations[c][0]); 
}; 

Aquí es un violín para demostrar: http://jsfiddle.net/MarkSchultheiss/JH7LR/

EDIT: Actualizado el ejemplo violín para pegar el material en un div. (utiliza un poco de jQuery que no era parte de la pregunta OP por lo que es "material añadido" hace una suposición que tiene un <div id='holdem'></div> en alguna parte.

$(locations).each(function(i) { 
    $('#holdem').prepend("<div>" + $(this)[0] + " Is at:" + this + "</div>"); 
}); 

Para un buen rato he actualizado el violín para mostrar el nombre del edificio como un enlace a la página de edificio:.! http://jsfiddle.net/MarkSchultheiss/JH7LR/3/

2
loc=json.results.bindings; 
tempar1=[]; 
tempar2=[]; 

for (i=0;i<loc.length;i++) {  
    for (prop in loc[i]) { 
     temp=loc[i][prop].value; 
     tempar1.push(temp); 
    } 
    tempar2.push(tempar1); 
    tempar1=[]; 
} 

Dónde JSON es igual al objeto JSON