How to parse JSON data with jQuery / JavaScript?

1,034,421

Solution 1

Assuming your server side script doesn't set the proper Content-Type: application/json response header you will need to indicate to jQuery that this is JSON by using the dataType: 'json' parameter.

Then you could use the $.each() function to loop through the data:

$.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
            }));
        });
    }
});

or use the $.getJSON method:

$.getJSON('/functions.php', { get_param: 'value' }, function(data) {
    $.each(data, function(index, element) {
        $('body').append($('<div>', {
            text: element.name
        }));
    });
});

Solution 2

Setting dataType:'json' will parse JSON for you:

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

Or else you can use parseJSON:

var parsedJson = $.parseJSON(jsonToBeParsed);

Then you can iterate the following:

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

...by using $().each:

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

JSFiddle

Solution 3

Try following code, it works in my project:

//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+'</>');
        }
    }
});

Solution 4

 $(document).ready(function () {
    $.ajax({ 
        url: '/functions.php', 
        type: 'GET',
        data: { get_param: 'value' }, 
        success: function (data) { 
         for (var i=0;i<data.length;++i)
         {
         $('#cand').append('<div class="name">data[i].name</>');
         }
        }
    });
});

Solution 5

I agree with all the above solutions, but to point out whats the root cause of this issue is, that major role player in all above code is this line of code:

dataType:'json'

when you miss this line (which is optional), the data returned from server is treated as full length string (which is default return type). Adding this line of code informs jQuery to convert the possible json string into json object.

Any jQuery ajax calls should specify this line, if expecting json data object.

Share:
1,034,421

Related videos on Youtube

Patrioticcow
Author by

Patrioticcow

spooky action at a distance

Updated on July 08, 2022

Comments

  • Patrioticcow
    Patrioticcow almost 2 years

    I have a AJAX call that returns some JSON like this:

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

    Inside the #cand div I'll get:

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

    How can I loop through this data and place each name in a div?

  • Patrioticcow
    Patrioticcow over 12 years
    success. thanks. DO i have to send json pr i can send anything from my php function?
  • Darin Dimitrov
    Darin Dimitrov over 12 years
    @Patrioticcow, you can send JSON as well. In this case you will need to set the contentType: 'application/json' setting in your $.ajax function and JSON serialize the data parameter, like that: data: JSON.stringify({ get_param: 'value' }). Then in your php script you would need to json decode to get back the original object.
  • Buttle Butkus
    Buttle Butkus over 9 years
    What is this "done: function"? Is that the same as "success"? I don't see it in the docs.
  • 151291
    151291 over 8 years
    My json data is {"0":{"level1":"done","level2":"done","level3":"no"}} how can extract this into each variables? i tried like this using $.each method but returns undefined var level1 = ele[0].level1;
  • 151291
    151291 over 8 years
    my json data is {"0":{"level1":"done","level2":"done","level3":"no"}} how can extract this into each variables? i tried like this using $.each method but returns undefined var level1 = ele[0].level1;
  • Rafay
    Rafay over 8 years
    @151291 thats not a proper way to ask your question, anyway here is the fiddle jsfiddle.net/fyxZt/1738 for your json. Note array notation json[0]
  • PHPFan
    PHPFan almost 5 years
    Thank you. helpful answer. How to get specified column value in a db table ?
  • Rafay
    Rafay almost 5 years
    @PHPFan you mean how to query database table? please provide more information and i would recommend asking a new question, with necessary details included.
  • PHPFan
    PHPFan almost 5 years
    @Rafay for example in this question if I want to get the name values only
  • TheCoderGuy
    TheCoderGuy over 4 years
    @DarinDimitrov How to show these data in a carousel bootstrap ?
  • Nagaraju Kasa
    Nagaraju Kasa over 2 years
    it helped me lot thank you so much