¿Cómo analizar datos JSON con jQuery / JavaScript?


Tengo una llamada AJAX que devuelve algo de JSON como este:

$(document).ready(function () {
    $.ajax({ 
        type: 'GET', 
        url: 'http://example/functions.php', 
        data: { get_param: 'value' }, 
        success: function (data) { 
            var names = data
            $('#cand').html(data);
        }
    });
});

Dentro del div #cand obtendré:

[ { "id" : "1", "name" : "test1" },
  { "id" : "2", "name" : "test2" },
  { "id" : "3", "name" : "test3" },
  { "id" : "4", "name" : "test4" },
  { "id" : "5", "name" : "test5" } ]

¿Cómo puedo recorrer estos datos y colocar cada nombre en un div?

Author: Brett DeWoody, 2012-01-21

10 answers

Suponiendo que su script del lado del servidor no establezca el encabezado de respuesta Content-Type: application/json adecuado, deberá indicar a jQuery que esto es JSON utilizando el parámetro dataType: 'json'.

Entonces usted podría utilizar el $.each() función para recorrer los datos:

$.ajax({ 
    type: 'GET', 
    url: 'http://example/functions.php', 
    data: { get_param: 'value' }, 
    dataType: 'json',
    success: function (data) { 
        $.each(data, function(index, element) {
            $('body').append($('<div>', {
                text: element.name
            }));
        });
    }
});

O utilice el método $.getJSON:

$.getJSON('/functions.php', { get_param: 'value' }, function(data) {
    $.each(data, function(index, element) {
        $('body').append($('<div>', {
            text: element.name
        }));
    });
});
 239
Author: Darin Dimitrov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-05 20:03:29

El ajuste dataType:'json' analizará json por usted

$.ajax({ 
                type: 'GET', 
                url: 'http://example/functions.php', 
                data: { get_param: 'value' }, 
                dataType:'json',
                success: function (data) { 
                                    var names = data
                    $('#cand').html(data);
                }
            });

, O bien se puede utilizar parseJSON

var parsedJson = $.parseJSON(jsonToBeParsed);

Aquí es cómo se puede iterar

var j ='[{"id":"1","name":"test1"},{"id":"2","name":"test2"},{"id":"3","name":"test3"},{"id":"4","name":"test4"},{"id":"5","name":"test5"}]';

Iterar usando each

var json = $.parseJSON(j);
$(json).each(function(i,val){
    $.each(val,function(k,v){
          console.log(k+" : "+ v);     
});
});

Http://jsfiddle.net/fyxZt/4 /

 63
Author: Rafay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-21 09:11:56

Intenta seguir el código, funciona en mi proyecto:

//start ajax request
$.ajax({
    url: "data.json",
    //force to handle it as text
    dataType: "text",
    success: function(data) {

        //data downloaded so we call parseJSON function 
        //and pass downloaded data
        var json = $.parseJSON(data);
        //now json variable contains data in json format
        //let's display a few items
        for (var i=0;i<json.length;++i)
        {
            $('#results').append('<div class="name">'+json[i].name+'</>');
        }
    }
});
 16
Author: Sarabhaiah Polakam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-15 18:45:26
 $(document).ready(function () {
    $.ajax({ 
        type: 'GET', 
        url: '/functions.php', 
        data: { get_param: 'value' }, 
        success: function (data) { 
         for (var i=0;i<data.length;++i)
         {
         $('#cand').append('<div class="name">data[i].name</>');
         }
        }
    });
});
 7
Author: Mohammed Abdelrasoul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-01 20:41:06

Usa ese código.

     $.ajax({

            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "Your URL",
            data: "{}",
            dataType: "json",
            success: function (data) {
                alert(data);
            },
            error: function (result) {
                alert("Error");
            }
        });
 4
Author: Shivam Srivastava,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-12 11:42:05

Ok tuve el mismo problema y lo arreglo así eliminando [] de [{"key":"value"}]:

  1. en su archivo php haga shure que imprime de esta manera
echo json_encode(array_shift($your_variable));
  1. en su función de éxito haga esto
 success: function (data) {
    var result = $.parseJSON(data);
      ('.yourclass').append(result['your_key1']);
      ('.yourclass').append(result['your_key2']);
       ..
    }

Y también puedes hacer un bucle si quieres

 3
Author: elaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-25 16:42:25
var jsonP = "person" : [ { "id" : "1", "name" : "test1" },
  { "id" : "2", "name" : "test2" },
  { "id" : "3", "name" : "test3" },
  { "id" : "4", "name" : "test4" },
  { "id" : "5", "name" : "test5" } ];

var cand = document.getElementById("cand");
var json_arr = [];
$.each(jsonP.person,function(key,value){
    json_arr.push(key+' . '+value.name  + '<br>');
    cand.innerHTML = json_arr;
});

<div id="cand">
</div>
 2
Author: Servesh Mishra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-14 06:43:03

Datos Json

data = {"clo":[{"fin":"auto"},{"fin":"robot"},{"fin":"fail"}]}

Cuando recupere

$.ajax({
  //type
  //url
  //data
  dataType:'json'
}).done(function( data ) {
var i = data.clo.length; while(i--){
$('#el').append('<p>'+data.clo[i].fin+'</>');
}
});
 1
Author: Guspan Tanadi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-11 03:34:40

Estoy de acuerdo con todas las soluciones anteriores, pero para señalar cuál es la causa raíz de este problema es, que el jugador principal en todo el código anterior es esta línea de código:

dataType:'json'

Cuando se pierde esta línea (que es opcional), los datos devueltos desde el servidor se tratan como cadena de longitud completa (que es el tipo de retorno predeterminado). Agregar esta línea de código informa a jQuery para convertir la posible cadena json en objeto json.

Cualquier llamada jQuery ajax debe especificar esta línea, si espera datos json objeto.

 1
Author: justnajm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-04 06:07:54
$.ajax({
  url: '//.xml',
  dataType: 'xml',
  success: onTrue,
  error: function (err) {
      console.error('Error: ', err);
  }
});

$('a').each(function () {
  $(this).click(function (e) {
      var l = e.target.text;
      //array.sort(sorteerOp(l));
      //functionToAdaptHtml();
  });
});
 0
Author: Sarah Smith,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-13 13:43:35