Scorrere l'elenco degli oggetti JSON
-
03-07-2019 - |
Domanda
Sto restituendo una lista < > da un servizio web come Elenco di oggetti JSON. Sto cercando di utilizzare un ciclo for per scorrere l'elenco e ottenere i valori dalle proprietà. Questo è un esempio del JSON di ritorno:
{"d":[{"__type":"FluentWeb.DTO.EmployeeOrder",
"EmployeeName":"Janet Leverling",
"EmployeeTitle":"Sales Representative",
"RequiredDate":"\/Date(839224800000)\/",
"OrderedProducts":null}]}
Quindi sto cercando di estrarre i contenuti usando qualcosa del genere:
function PrintResults(result) {
for (var i = 0; i < result.length; i++) {
alert(result.employeename);
}
Come dovrebbe essere fatto?
Soluzione
ha avuto lo stesso problema oggi, il tuo argomento mi ha aiutato, quindi ecco la soluzione;)
alert(result.d[0].EmployeeTitle);
Altri suggerimenti
Fai attenzione, d
è l'elenco.
for (var i = 0; i < result.d.length; i++) {
alert(result.d[i].employeename);
}
È vicino! Prova questo:
for (var prop in result) {
if (result.hasOwnProperty(prop)) {
alert(result[prop]);
}
}
Aggiornamento:
Se il tuo risultato è veramente un array di un oggetto, potresti doverlo fare:
for (var prop in result[0]) {
if (result[0].hasOwnProperty(prop)) {
alert(result[0][prop]);
}
}
O se vuoi scorrere ogni risultato nell'array se ce ne sono altri, prova:
for (var i = 0; i < results.length; i++) {
for (var prop in result[i]) {
if (result[i].hasOwnProperty(prop)) {
alert(result[i][prop]);
}
}
}
Eccolo:
success:
function(data) {
$.each(data, function(i, item){
alert("Mine is " + i + "|" + item.title + "|" + item.key);
});
}
Testo JSON di esempio:
{"title": "camp crowhouse",
"key": "agtnZW90YWdkZXYyMXIKCxIEUG9zdBgUDA"}
Dato che stai usando jQuery, potresti anche usare ogni metodo ... Inoltre, sembra che tutto sia un valore della proprietà 'd' in questo oggetto JS [Notazione].
$.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);
});
});
Dovrebbe funzionare. in caso contrario, forse potresti darci un esempio più lungo di JSON.
Modifica: se nessuna di queste cose funziona, allora sto iniziando a pensare che potrebbe esserci qualcosa di sbagliato nella sintassi del tuo JSON.
var d = $.parseJSON(result.d);
for(var i =0;i<d.length;i++){
alert(d[i].EmployeeName);
}
Funzionerà!
$(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" }]
*/
}
});
});
La cosa principale su questo è usare la proprietà esattamente come l'attributo della coppia chiave-valore JSON.
Ho la seguente chiamata:
$('#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 struttura che ritorna dal server assomiglia a:
{"result":{"1":"waterskiing","2":"canoeing","18":"windsurfing"}}