Search code examples
javascriptangularjsjsonangular-resource

How to convert string of objects to JSON object in angular transformRequest


So I'm receiving this string:

{"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)"}

here in console.log(data):

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

How do I convert data into a JSON array?? I already tried JSON.parse(data) but it throws an error.


Solution

  • If you want the data as an array, you might wanna set isArray to true

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

    This is assuming that the string representation you receive is in valid format. I can see that , is missing after each object. Is this expected? If yes, you might want to replace } with },, wrap them in '[]' and then do angular.fromJson(data) in the transformer.

    Here's a plunker that does just that: https://plnkr.co/edit/ZGLK7PTclapVNwuIlM1T?p=preview