Recorrer la lista de objetos JSON
-
03-07-2019 - |
Pregunta
Estoy devolviendo una Lista < > de un servicio web como una Lista de objetos JSON. Estoy tratando de usar un bucle for para recorrer la lista y obtener los valores de las propiedades. Esta es una muestra del JSON que regresa:
{"d":[{"__type":"FluentWeb.DTO.EmployeeOrder",
"EmployeeName":"Janet Leverling",
"EmployeeTitle":"Sales Representative",
"RequiredDate":"\/Date(839224800000)\/",
"OrderedProducts":null}]}
Así que estoy tratando de extraer el contenido usando algo como esto:
function PrintResults(result) {
for (var i = 0; i < result.length; i++) {
alert(result.employeename);
}
¿Cómo se debe hacer esto?
Solución
tuve el mismo problema hoy, Tu tema me ayudó, así que aquí va la solución;)
alert(result.d[0].EmployeeTitle);
Otros consejos
Tenga cuidado, d
es la lista.
for (var i = 0; i < result.d.length; i++) {
alert(result.d[i].employeename);
}
¡Está cerca! Prueba esto:
for (var prop in result) {
if (result.hasOwnProperty(prop)) {
alert(result[prop]);
}
}
Actualización:
Si su resultado es realmente una matriz de un objeto, entonces puede que tenga que hacer esto:
for (var prop in result[0]) {
if (result[0].hasOwnProperty(prop)) {
alert(result[0][prop]);
}
}
O si desea recorrer cada resultado en la matriz si hay más, intente:
for (var i = 0; i < results.length; i++) {
for (var prop in result[i]) {
if (result[i].hasOwnProperty(prop)) {
alert(result[i][prop]);
}
}
}
Aquí está:
success:
function(data) {
$.each(data, function(i, item){
alert("Mine is " + i + "|" + item.title + "|" + item.key);
});
}
Texto JSON de muestra:
{"title": "camp crowhouse",
"key": "agtnZW90YWdkZXYyMXIKCxIEUG9zdBgUDA"}
Dado que está utilizando jQuery, podría utilizar cada método ... Además, parece que todo es un valor de la propiedad 'd' en este objeto JS [Notación].
$.each(result.d,function(i) {
// In case there are several values in the array 'd'
$.each(this,function(j) {
// Apparently doesn't work...
alert(this.EmployeeName);
// What about this?
alert(result.d[i][j]['EmployeeName']);
// Or this?
alert(result.d[i][j].EmployeeName);
});
});
Eso debería funcionar. si no, entonces quizás pueda darnos un ejemplo más extenso del JSON.
Editar: Si nada de esto funciona, estoy empezando a pensar que podría haber algo mal con la sintaxis de su JSON.
var d = $.parseJSON(result.d);
for(var i =0;i<d.length;i++){
alert(d[i].EmployeeName);
}
¡Esto funcionará!
$(document).ready(function ()
{
$.ajax(
{
type: 'POST',
url: "/Home/MethodName",
success: function (data) {
//data is the string that the method returns in a json format, but in string
var jsonData = JSON.parse(data); //This converts the string to json
for (var i = 0; i < jsonData.length; i++) //The json object has lenght
{
var object = jsonData[i]; //You are in the current object
$('#olListId').append('<li class="someclass>' + object.Atributte + '</li>'); //now you access the property.
}
/* JSON EXAMPLE
[{ "Atributte": "value" },
{ "Atributte": "value" },
{ "Atributte": "value" }]
*/
}
});
});
Lo principal de esto es usar la propiedad exactamente igual que el atributo del par clave-valor JSON.
Tengo la siguiente llamada:
$('#select_box_id').change(function() {
var action = $('#my_form').attr('action');
$.get(action,{},function(response){
$.each(response.result,function(i) {
alert("key is: " + i + ", val is: " + response.result[i]);
});
}, 'json');
});
La estructura que regresa del servidor se ve así:
{"result":{"1":"waterskiing","2":"canoeing","18":"windsurfing"}}