如何在angular transformRequest中将对象字符串转换为JSON对象

时间:2016-01-16 05:40:35

标签: javascript angularjs json angular-resource

所以我收到了这个字符串:

{"id":"0-worfebvjyyvqjjor","size":17,"price":921,"face":"( .-.)","date":"Mon Jan 04 2016 22:55:30 GMT+0000 (GMT Standard Time)"}
{"id":"1-ifma3yxxccgzaor","size":19,"price":98,"face":"( .o.)","date":"Fri Jan 08 2016 16:11:25 GMT+0000 (GMT Standard Time)"}
{"id":"2-sa3iurvt4hv0lik9","size":14,"price":659,"face":"( `·´ )","date":"Sun Jan 03 2016 06:20:28 GMT+0000 (GMT Standard Time)"}
{"id":"3-bc3tf55q9vx11yvi","size":33,"price":361,"face":"( ° ͜ ʖ °)","date":"Fri Jan 01 2016 22:49:22 GMT+0000 (GMT Standard Time)"}

这里是console.log(数据):

var WareHouseResource = $resource('/api/products?limit=10', {}, {
    query: {
        method: 'GET',
        isArray: false,
        transformResponse: function(data) {
            console.log(data);
        }
    }
});

如何将数据转换为JSON数组?我已经尝试过JSON.parse(数据),但它会抛出错误。

2 个答案:

答案 0 :(得分:1)

如果您希望将数据作为数组,则可能需要将isArray设置为true

var WareHouseResource = $resource('/api/products?limit=10', {}, {
    query: {
        method: 'GET',
        isArray: true
    }
});

这假设您收到的字符串表示格式有效。我可以看到每个对象后都缺少,。这是预期的吗?如果是,您可能希望将}替换为},,将其包装在' []'然后在变压器中执行angular.fromJson(data)

这是一个能够做到这一点的人:https://plnkr.co/edit/ZGLK7PTclapVNwuIlM1T?p=preview

答案 1 :(得分:0)

您需要使用angular.fromJson()。所以

var WareHouseResource = $resource('/api/products?limit=10', {}, {
    query: {
        method: 'GET',
        isArray: false,
        transformResponse: function(data) {
            console.log(angular.fromJson(data));
        }
    }
});

查看https://docs.angularjs.org/api/ng/function/angular.fromJson

var items=[{"id":"0-worfebvjyyvqjjor","size":17,"price":921,"face":"( .-.)","date":"Mon Jan 04 2016 22:55:30 GMT+0000 (GMT Standard Time)"},
{"id":"1-ifma3yxxccgzaor","size":19,"price":98,"face":"( .o.)","date":"Fri Jan 08 2016 16:11:25 GMT+0000 (GMT Standard Time)"},
{"id":"2-sa3iurvt4hv0lik9","size":14,"price":659,"face":"( `·´ )","date":"Sun Jan 03 2016 06:20:28 GMT+0000 (GMT Standard Time)"},
{"id":"3-bc3tf55q9vx11yvi","size":33,"price":361,"face":"( ° ͜ ʖ °)","date":"Fri Jan 01 2016 22:49:22 GMT+0000 (GMT Standard Time)"}]

alert(angular.fromJson(items))
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>