loviji
loviji

Reputation: 13080

how to manipulate Json response like an object?

my jQuery.ajax return JSon object. I firstly read other articles. but their response text not likes mine. My Response content: from firebug response

{"item":"[{\"country\":\"USA\",\"lan\":\"EN\"},{\"country\":\"Turkiye\",\"lan\":\"TR\"}]"}

Now i trying to alert countryName:

$('#loadData').click(function() {
            $.ajax({
                type: "POST",
                url: "WS/myWS.asmx/getDaa",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                $("#jsonResponse").html(msg);
                    $.each(msg.item, function(i, d) {
                        alert(this.country);
                        debugger;
                    });
                },
            });
        });

but it is alerting "undefined"

Upvotes: 3

Views: 8978

Answers (3)

jitter
jitter

Reputation: 54605

The value of item is a string. Thus you first need to parse it as json. Try this.

$("#jsonResponse").html(msg);
    var item = jQuery.parseJSON(msg.item)
    $.each(item, function(i, d) {
        alert(this.country);
        debugger;
    });
},

Upvotes: 9

Dancrumb
Dancrumb

Reputation: 27529

The reason is that msg.item is a string.

The reason that it is a string is that initial double quote you have after item:. This also explains why your double quotes are escaped. You have:

{"item":"[{\"country\":\"USA\",\"lan\":\"EN\"},{\"country\":\"Turkiye\",\"lan\":\"TR\"}]"}

When you should have:

{"item":[{"country":"USA","lan":"EN"},{"country":"Turkiye","lan":"TR"}]"}

Upvotes: 2

David V.
David V.

Reputation: 5708

{"item":"[{\"country\":\"USA\",\"lan\":\"EN\"},{\"country\":\"Turkiye\",\"lan\":\"TR\"}]"}
        ^
        |
        +---- It's a string, not an array !

Your JSON should look like

{"item":[ {"country":"USA","lan":"EN"},{"country":"Turkiye","lan":"TR"}]}

Then you can access it like

country = msg.item[0];
lang    = country.lan;

for (i=0; i< item.length; i++) { alert ( item[i].country); }

etc...

Upvotes: 7

Related Questions