D.B D.B - 3 months ago 12
Ajax Question

Get value from an odata property in a JSON response using ajax

I need to get the value for @odata.context property from the following Json response in ajax:

{
"@odata.context":"https://site.sharepoint.com/_api/",
"@odata.type":"#oneDrive.permission",
"@odata.id":"https",
"link":{"scope":"anonymous"}
}


I would like to do something like that in code:

$.ajax({
type: "POST",
beforeSend: function (request) {
request.setRequestHeader("Authorization", 'Bearer ' + bearerToken);
},
url: serverUrl,
data: JSON.stringify(params),
dataType: 'json',
contentType: " application/json",
success: function (data) {
var myvalue= data.@odata.context; // ****???
var jsonObject = JSON.parse(data); //this line throws an error Unexpected token o in JSON at position 1

}
});

Answer

I think you can get data by this:

data["@odata.context"]

And about the JSON.parse throw exception, it caused by the data is not a JSON string.

Example