I can't get the data of a JSON object.
This is my API action:
public string GetVideoInfo(uint videoID)
{
ApiVideoInfo videoInfo = new ApiVideoInfo()
{
Likes = BitVidDb.GetLikes(videoID),
Dislikes = BitVidDb.GetDislikes(videoID),
Views = BitVidDb.GetViews(videoID),
};
return JsonConvert.SerializeObject(videoInfo);
}
If i call the API in the browser it returns:
"{\"Views\":396,\"Likes\":1,\"Dislikes\":0}"
However when i call this ajax function:
$.ajax({
url: '/API/Video/GetVideoInfo/25',
dataType: 'application/json',
complete: function (data) {
var json = JSON.parse(data);
alert(json["Views"]);
},
});
It gives me the following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
I've used JSON.stringify
to convert it to a string and it outputs this:
{"readyState":4,"responseText":"\"{\\\"Views\\\":396,\\\"Likes\\\":1,\\\"Dislikes\\\":0}\"","status":200,"statusText":"OK"}
Is there some additional step I need to take to extract the values? The request seems to be fine, Chrome dev tools gives this as the answer to the api:
JSON
{"Views":396,"Likes":1,"Dislikes":0}
Thanks in advance
Jan
You can only parse strings and data is an object. To get the json as string i just needed to use data.responseText instead.
$.ajax({
url: '/API/Video/GetVideoInfo/25',
dataType: 'application/json',
complete: function (data) {
var json = JSON.parse(data.responseText);
alert(json["Views"]);
},
});