7

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

2
  • 1
    No such thing in JavaScript as "JSON object". There is JSON (which is a particularly formatted string), and there is JS object (which is a type in JavaScript). Which one of those do you have? And what is the output you want, since the description is similarly vague? (EDIT: there actually does exist a JSON object: JSON (the one with parse and stringify functions; I am 100% positive that's not what you are talking about) Commented May 8, 2015 at 3:51
  • var obj = JSON.parse(jsoninfo); Commented May 8, 2015 at 3:53

4 Answers 4

11

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)
})
Sign up to request clarification or add additional context in comments.

Comments

2

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'/>

Comments

0

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

Comments

0

one way is to iterate over your json object using each function and get the values.

$.each(jsonObject,function(i.field){
id=field.id;
name=field.name;
});

or can get Array of objects using JSON.parse(JSON.stringify(jsonObject))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.