How to parse JSON data with jQuery / JavaScript?
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 })); });});
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); });});
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+'</>'); } }});