King_Fisher King_Fisher - 1 month ago 11
jQuery Question

How to read data from json format using jquery

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();

}

Answer

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>