Coding Away Coding Away - 3 months ago 9
AngularJS Question

How to filter out wrapper from json from either js file in json format or from web api

I have JSON data that I need to filter out as the format is not easy for me to consume.

It is easy when my data is like this:

[
{
"DeviceId": "AAIrmgAAAAEAAQ==",
"Id": 15,
"Name": "QUERY TASK",
"Context": "{\r\n \"did\": \"00022B9A000000010001\",\r\n \"ps\": -1,\r\n \"hostName\": \"bzs-dptpre-002.com\",\r\n \"ipAddress\": \"10.22.125.99\"\r\n}",
"Timestamp": "2016-08-26T16:02:15.747"
}
]


Instead I always have JSON (from JavaScript files or coming from Web Api) that look like this:

{
"DeviceEvents": [
{
"DeviceId": "AAIrmgAAAAEAAQ==",
"Id": 15,
"Name": "QUERY TASK",
"Context": "{\r\n \"did\": \"00022B9A000000010001\",\r\n \"ps\": -1,\r\n \"hostName\": \"bzs-dptpre-002.com\",\r\n \"ipAddress\": \"10.22.125.99\"\r\n}",
"Timestamp": "2016-08-26T16:02:15.747"
}
]
}


The way in which I consume the data is with both Angular 1.5.x and Angular 2.

Now I can easily get at the data correctly if I use
$http.get
like this:

$http.get('api/devices.json') // can be a real Web API call
.then(function (result) {
vm.devices = result.data.DeviceEvents;


However this is easy with above, but the standards I am using are using $resource and $httpBackend and thus I don't see how to do the
result.data.DeviceEvents
.

So this is how I am doing Angular 1 with
$httpBackend
:

var deviceUrl = "/api/devices"; // routing
var devices = "[{ ... }]"; // json data


Seems that this works if I remove
DeviceEvents
from the JSON file.

$httpBackend.whenGET(deviceUrl).respond(devices);


I have tried this and it does not work (something about
$httpBackend
is not allowing this array).

$httpBackend.whenGET(deviceUrl).respond(devices.DeviceEvents);


So even with Angular2 I don't see how to filter it either:

Angular 2 example

private _deviceUrl= 'api/devices/devices.json';

constructor(private _http: Http) { }

getDevices(): Observable<IDevice[]> {
return this._http.get(this._deviceUrl)
.map((response: Response) => <IDevice[]>response.json())
.do(data => console.log("All: " + JSON.stringify(data)))
.catch(this.handleError);
}


So part of my issues are around not knowing how to manipulate the json in both JavaScript and Angular... Any help is appreciated.

Answer

With the Angular2 example - I would need more information and test that a bit.

However, regardless of whether you are using $http, $resource or $httpBackend , you can get this to work in the same way

I suspect that you have maybe a few pages like listing your data and specific detail page.

Try this

console.log(devices.DeviceEvents.length);  
$httpBackend.whenGET(deviceUrl).respond(devices.DeviceEvents);

Perhaps it works on some page and not on another? Well look for things that you might have copied or did from a book or video

devices.DeviceEvents[i].SomeThing ....