I have json array like this one:

[{"code" : "A1", "desc" : "desc1"},{"code" : "A2", "desc" : "desc2"}]

How should i parse it in jquery to get data like this:

A1 - desc1
A2 - desc2

I tried lots of different ways, but none of them works. At the moment i have a code like this:

$.ajax({
    url: 'my_url',
    success: function(data) {
        $.each(data, function (key, val) {
            alert(val.code);
        });
    },
    error: function() {
        alert('problem');
    }
});
share|improve this question
1  
You need to use $.parseJSON on data – nhahtdh Oct 11 '12 at 17:05
feedback

3 Answers

Use

jQuery.parseJSON( json )

Change code to

$.ajax({
   url: 'my_url',
   success: function(data) {
      var jsonData = jQuery.parseJSON(data);
      $.each(jsonData, function (key, val) {
        alert(val.code);
      });
  },
  error: function() {
    alert('problem');
  }
});

EDIT: Working fiddle

Cheers!!

share|improve this answer
I tried your solution, but it does not work. Previously it alerted "undefined" and now i don't get any alert. – JNM Oct 11 '12 at 17:09
check link above. – bhb Oct 11 '12 at 17:14
feedback

You can also try setting the

dataType:'json' // to your ajax request

After adding this try to check with parseJson and sans parseJson

share|improve this answer
+1 for thinking differently :) – bhb Oct 11 '12 at 17:28
@bhb .. Thanks :) – Sushanth -- Oct 11 '12 at 17:30
feedback
up vote 0 down vote accepted

Ok, i solved my problem. The problem was my hosting provider. I am using Codeigniter as a framework, and return result as json. My hosting provides adds 3 additional lines to the result (uses them for tracking opened pages). Problem was, that i was checking json, which i see in browser, but when i rightclicked and checked source code, i found those lines.

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.