How to decode a JSON object and iterate over it?

In this post, I learned how to encode an object on the server side, and now I would like to decode it on the client side.

On the client side, I do

$.ajax({ type: "GET", url: "/cgi-bin/ajax_sort.pl", contentType: "application/json; charset=utf-8", dataType: "json", data: { "column" : this.id }, error: function(XMLHttpRequest, textStatus, errorThrown) { showError('responseText: ' + XMLHttpRequest.responseText); showError('textStatus: ' + textStatus); showError('errorThrown: ' + errorThrown); }, success: function(result){ if (result.error) { showError(result.error); } else { var obj = jQuery.parseJSON(result); } } }); 

Question

Does obj now have decoded JSON data?

If so, the object looks like it is on the server side (output from Perl Data::Dumper )

 $VAR1 = { '127' => { 'owners' => [ 'm' ], 'users' => [ 'hh', 'do' ], 'date_end' => '24/05-2011', 'title' => 'dfg', 'date_begin' => '24/05-2011', 'members_groups' => [], 'type' => 'individuel' }, '276' => { ... 

Question

Is obj really contains decoded JSON, how can I iterate over an object?

+4
source share
4 answers

Since you specified dataType: 'json' , result should already contain a Javascript object that is uneserialized from the HTTP response. $.parseJSON not needed.

You can pass it through $.each :

 success: function(result){ if (result.error) { showError(result.error); } else { $.each(result, function(key, value) { alert(value.title). }); } } 
+5
source

result already a JSON object - jQuery is parsing, since you specified dataType: "json" - so you should not parse it.

To view the data, you can do this:

 for(key in result){ var curr = result[key]; //iterate over owners for(var i = 0; i < curr.owners.length; i++){ alert(curr.owners[i]); } //iterate over users for(var i = 0; i < curr.users.length; i++){ alert(curr.users[i]); } alert(curr.data_end); alert(curr.title); //and so on... } 

Update

I keep forgetting about $.each() , as shown in the lonsomeday answer - you can go with this instead.

+1
source

You need to declare the data type of your AJAX request as JSON. jQuery will automatically "decrypt" this and create an object from it.

You can immediately access data through alert( result[127] );

+1
source

You can iterate over obj elements with for...in .

 for(var key in obj) { var value = obj[key]; alert(key + "=" + value); } 

Note. There should be no reason why you want to iterate over the elements of a JSON object. JSON is intended as a serialization format where both parties (client and server) know their structure. If you can help what data is being transmitted, obj should be an array in its largest area.

+1
source

All Articles