2

Here is a snippet of javascript from my C# web MVC application:

$.ajax({
         url: 'myurl'
        }).done(function(response) {
          $scope.Vdata = JSON.parse(response);
          return $scope.$apply();
        });

The JSON response form this call looks like this

"{
    \"renditions\": {
        \"live\": \"true\",
        \" type\": \"default\",
        \"rendition\": {
            \"name\": \"Live \",
            \"url\": \"http: //mysite\"
        }
    }
}"

I would like to wrap the json response rendition object into an array to look like this-(note the added square brackets for the array)

"{
    \"renditions\": {
        \"live\": \"true\",
        \" type\": \"default\",
        \"rendition\": [{
            \"name\": \"Live \",
            \"url\": \"http: //mysite\"
        }]
    }
}"

I tried something like this which didn’t work:

$.ajax({
    url: 'myurl'
}).done(function(response) {
    var tmp;
    if (!respose.renditons.rendition.isArray) {
        tmp = respose.renditions.renditon;
        respose.renditon = [];
        respose.renditon.push(tmp);
    }
    $scope.Vdata = JSON.parse(response);
    return $scope.$apply();
});

The response will sometimes include the rendition object as an array so I only need to convert to an array in cases where its not.

Can someone please help me with the correct javascript to convert the json object into an array. Preferably modifying my existing code

4

3 回答 3

0

尝试这个:

$.ajax({
    url: 'myurl'
}).done(function(response) {
    var json = JSON.parse(response);
    if(!Array.isArray(json.renditions.rendition)) {
        json.renditions.rendition = [json.renditions.rendition];
    }
    return json;
});

小提琴演示(有点......)

于 2013-07-24T18:25:33.157 回答
0

您可以使用以下方法检查对象是否为数组:

Object.prototype.toString.call( response.renditions.rendition ) === '[object Array]'

您可以简化到数组的转换——只需使用以下命令将其包装为数组x = [x]

if (Object.prototype.toString.call( response.renditions.rendition ) !== '[object Array]') {
    response.renditions.rendition = [response.renditions.rendition];
}

小提琴演示。

于 2013-07-24T18:17:45.170 回答
-1

将数据类型 JSON 添加到您的 ajax 帖子中。例子

$.ajax({type: "POST",
        url: URL, 
        data: PARAMS,
        success: function(data){
            //json is changed to array because of datatype JSON
                alert(data.renditions);
            },            
        beforeSend: function (XMLHttpRequest) { 
            /* do something or leave empty */
        },
            complete: function (XMLHttpRequest, textStatus) { /*do something or leave empty */ },  
        dataType: "json"}
       );
于 2013-07-24T18:37:20.003 回答