简体   繁体   中英

Parse ajax json response

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 get 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"]);
    },
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM