1

enter image description here

How to read data from json format using jquery. below is what i have tried, but unfortualtly i couldn't able to read exact data which i want.

 $.ajax({
            url: '@Url.HttpRouteUrl("GetDistrictList", new { })',
            type: 'GET',
            datatype: "json",
            success: function (data, txtStatus, xhr) {
                console.log(data);
                if (data != null) {

                    $.each(data, function (i, item) {
                        alert(data[0]);
                        alert(data[0].DistrictCode)
                        alert(item);
                        alert(item[0]);
                        alert(item.DistrictCode);
                        $('#tblDistricts > tbody').append('<tr><td>'+item.DistrictCode+'</td><td>test</td><td>test</td><td>test</td><td>test</td><td>test</td></tr>');

                    })
                }
            },
            error: function (xhr, textStatus, errorThrown) { 
                console.log("error in GetDistrictList : " + errorThrown);
            }
        });'

In alert box , I'm getting 'undefined' or '[object] [Object] only, I could not able to read exact data. I got stuck here.

Edit: Web api will return the data as List objects.

[HttpGet]
        [Route("GetDistrict/", Name = "GetDistrictList")]
        public List<DistrictModels> GetDistrictList()
        {

            BAL_District oBAL_District = new BAL_District();

            return oBAL_District.GetDistrictList();

        }

5 Answers 5

2

Use var Data = $.parseJSON(response);

Example

var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );

JSON.stringify turns a Javascript object into JSON text and stores that JSON text in a string.

JSON.parse turns a string of JSON text into a Javascript object.

How to access JSON object

FYI, as of jQuery 3.0, $.parseJSON is deprecated. To parse JSON objects, use the native JSON.parse method instead.

var json = [ 
     { 'red': '#f00' },
     { 'green': '#0f0' },
     { 'blue': '#00f' }
];
$.each(json, function () {
  $.each(this, function (name, value) {
    console.log(name + '=' + value);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

6 Comments

I'm returning as List objects from my web api controller
See I've updated my answer, How to use each for JSON object.
@King_Fisher Did you understand what I am trying to explain in my updated answer with an example. How iterate JSON object in loop.
I hope you can able to see the data format from the picture.can you given an example from those data.
|
0

I think you wish to call this function - http://api.jquery.com/jquery.parsejson/

Comments

0

if you are getting [object,object] it means you have already fetched the Json Object. And if you need some clarifications, please share the expected Json you want.Thanks

1 Comment

As you can see in attached picture, I got data from the web api, I just want to populate the data into html table.
0

Use JSON.stringify(object). It is super safe way to print out.

   $.ajax({
        url: '@Url.HttpRouteUrl("GetDistrictList", new { })',
        type: 'GET',
        datatype: "json",
        success: function (data, txtStatus, xhr) {
            console.log(data);
            if (!!data) {
                // '!data' means data variable is not available and '!!data' returns true:boolean if variable is valid

                //idx is 'index', I made the code as a loop. It will not work if array is empty. 
                //It is good way to avoid error
                for(var idx in data){
                    if(idx == 0) {
                        //JSON.stringify makes object type to string type. It is safe to use since it is a native javascript function
                        alert(JSON.stringify(data[idx]);
                        //You can access member by 'data[idx].memberName'
                        //DOM adding code can be here
                    }
                }
            }
        },
        error: function (xhr, textStatus, errorThrown) { 
            console.log("error in GetDistrictList : " + errorThrown);
        }
    });

Comments

0

Assuming your server side script doesn't set the proper Content-Type: application/json response header you will need to indicate to jQuery that this is JSON by using the dataType: 'json' parameter.

You should not use data variable in $.each(). Then you could use the $.each() function to loop through the data:

$.ajax({
    url: '@Url.HttpRouteUrl("GetDistrictList", new { })',
    type: 'GET',
    datatype: "json",
    success: function (data, txtStatus, xhr) {
        console.log(data);
        if (data != null) {

            $.each(data, function (index, element) {
                alert(element);
                alert(element[0]);
                alert(element.DistrictCode);
                $('#tblDistricts > tbody').append('<tr><td>'+element.DistrictCode+'</td><td>test</td><td>test</td><td>test</td><td>test</td><td>test</td></tr>');
            });
        }
    },
    error: function (xhr, textStatus, errorThrown) { 
        console.log("error in GetDistrictList : " + errorThrown);
    }
});'

or use the $.getJSON method: For example:

$.getJSON('/functions.php', { get_param: 'value' }, function(data) {
    $.each(data, function(index, element) {
        $('body').append($('<div>', {
            text: element.name
        }));
    });
});

Note: As of jQuery 3.0, $.parseJSON is deprecated. To parse JSON objects, use the native JSON.parse method instead.

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.