Chamith Chamith - 5 months ago 18
JSON Question

How to extract an element from a Json Response in Jquery

I have an ASP.Net MVC Application and I got a

JSON
response from the server using this code segment.

public JsonResult GetVehicleByID(string VehicleID)
{
db.Configuration.ProxyCreationEnabled = false;

var res = from type in db.Vehicles
where type.ID == VehicleID
select new
{
ID = type.ID,
RegNo = type.RegNo
};
return Json(res, JsonRequestBehavior.AllowGet);
}


The code above returns the following
Json
(Google Postman)

[
{
"ID": "000001",
"Type": "Internal"
}
]


I handled the response using following jQuery Ajax

function GetVehicle(id) {
$.ajax({
async: true,
url: "GetVehicleByID?VehicleID=" + id,
cache: false,
dataType: "json",
contentType: "application/json",
success: function (data) {

//Parsing Method 1
//var a = jQuery.parseJSON(data);
//console.log(a.Type);

//Parsing Method 2
var b = $.parseJSON(data);
console.log(b['Type']);
}
});
}


I was unable to extract the
Type
element from this response. There are several similar questions in the Stack Overflow & solutions of those questions are about parsing. I tried to parse in 2 ways but the browser log gives following error


Uncaught SyntaxError: Unexpected token o in JSON at position 1


Helping is highly appreciated than flagging this question as duplicate.

Answer

Try just console.log(data[0].Type). I believe jQuery is already parsing the response as JSON for you because you specified dataType: "json" and the response from the server had the right Content-Type header.