I have the following array of json object
[{"id":10,"name":"sinu"},{"id":20,"name":"shinto"}]
How can i parse this using jquery and get names, id of each one.
thanks in advance
var data = [{"id":10,"name":"sinu"},{"id":20,"name":"shinto"}];
jQuery(data).each(function(i, item){
$('#output').append(item.id + ' ' + item.name + '<br>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>
var data = [{"id":10,"name":"sinu"},{"id":20,"name":"shinto"}];
jQuery(data).each(function(i, item){
console.log(item.id, item.name)
})
Use json2.js and parse your array of json object. See the working code below,
var data = '[{"id":10,"name":"sinu"},{"id":20,"name":"shinto"}]';
var obj = JSON.parse(data);
var append= '';
$.each(obj, function(i, $val)
{
append+= $val.id + ',';
});
$('#ids').text(append);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://github.com/douglascrockford/JSON-js/blob/master/json2.js"></script>
<label id='ids'/>
Use the jQuery.parseJSON() method:
var arr = jQuery.parseJSON( '[{"id":10,"name":"sinu"},{"id":20,"name":"shinto"}]' );
for (var i = 0; i < arr.length; i++) {
console.log('index: ' + i + ', id: ' + arr[i].id + ', name: ' + arr[i].name);
}
That code will log this to your console:
index: 0, id: 10, name: sinu
index: 1, id: 20, name: shinto
JSON(the one withparseandstringifyfunctions; I am 100% positive that's not what you are talking about)