How to manipulate Json response as an object?

my jQuery.ajax returns a JSon object. At first I read other articles. but I don’t like their response text. Content of my answer : from firebug answer

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

Now I am trying to call 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 he warns "undefined"

+3
source share
3 answers

The value of an element is a string. So you first need to parse it as json. Try it.

$("#jsonResponse").html(msg);
    var item = jQuery.parseJSON(msg.item)
    $.each(item, function(i, d) {
        alert(this.country);
        debugger;
    });
},
+9
source
{"item":"[{\"country\":\"USA\",\"lan\":\"EN\"},{\"country\":\"Turkiye\",\"lan\":\"TR\"}]"}
        ^
        |
        +---- It a string, not an array !

Your JSON should look like

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

Then you can access it, for example

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

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

etc...

+7
source

, msg.item - .

, , , item:. , . :

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

:

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

Source: https://habr.com/ru/post/1737157/


All Articles