# How to handle nested JSON

**URL:** <https://forum.ionicframework.com/t/how-to-handle-nested-json/51056>\
**Category:** ionic-v3\
**Created:** [May 3, 2016, 11:28am UTC](https://forum.ionicframework.com/t/how-to-handle-nested-json/51056 "2016-05-03T11:28:45Z")\
**Posts on this page:** 13\
**Page:** 1

<div class="post-metadata">

**Author:** ![realjumy](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/realjumy/32/99741_2.png) [@realjumy](https://forum.ionicframework.com/u/realjumy)\
**Post date:** [May 3, 2016, 11:28am UTC](https://forum.ionicframework.com/t/how-to-handle-nested-json/51056/1 "2016-05-03T11:28:45Z")

</div>

Hello everyone.

I’m trying to handle JSON answers from my server but I’m having serious difficulties with the nested information in the JSON.

The current JSON is:

```
{
    "item": {
        "id": 1,
        "name": "The name",
        "overall_quality": 3,
        "extra_info": "Some extra info",
        "locations": [
            {
                "id": 2,
                "item_id": 1,
                "lat": 22.12212,
                "lon": -3.48485,
                "town": "Bristol",
                "zoom": 0.99,
                "mall_id": 1,
                "branch_id": 2
            }
        ]
    }

```

Using the following code I retrieve the information properly:

```
retrieveJSON(route) {
var url = 'encodeURI(route)';
console.log(url);
var response = {content:null};
this.response = this.http.get(url).map(res => res.json());
return this.response;
}

```

But the information inside “locations” is missing. What I actually receive is just:

> {id: 1, name: “The name”, overall\_quality: 3, extra\_info: “Some extra info”}

Has anyone any suggestion on how to fix this? I have been trying to find the answer for 4 days and I can’t make it work properly…

Thanks.

---

<div class="post-metadata">

**Author:** ![mauricionarcizo](https://avatars.discourse-cdn.com/v4/letter/m/e68b1a/32.png) [@mauricionarcizo](https://forum.ionicframework.com/u/mauricionarcizo)\
**Post date:** [May 3, 2016, 11:46am UTC](https://forum.ionicframework.com/t/how-to-handle-nested-json/51056/2 "2016-05-03T11:46:32Z")

</div>

Hi!

You are sure which your server is sending the property ‘locations’ in response?

---

<div class="post-metadata">

**Author:** ![realjumy](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/realjumy/32/99741_2.png) [@realjumy](https://forum.ionicframework.com/u/realjumy)\
**Post date:** [May 3, 2016, 11:48am UTC](https://forum.ionicframework.com/t/how-to-handle-nested-json/51056/3 "2016-05-03T11:48:28Z")

</div>

I think so. I just copy-pasted the response that I obtained when I call the JSON. I think everything is normal…

---

<div class="post-metadata">

**Author:** ![mauricionarcizo](https://avatars.discourse-cdn.com/v4/letter/m/e68b1a/32.png) [@mauricionarcizo](https://forum.ionicframework.com/u/mauricionarcizo)\
**Post date:** [May 3, 2016, 11:56am UTC](https://forum.ionicframework.com/t/how-to-handle-nested-json/51056/4 "2016-05-03T11:56:13Z")

</div>

Humm…

So, print your body response, like this:

`this.response = this.http.get(url).map(res => { console.log(res._body); return res.json(); });`

And see if the ‘\_body’ has the property ‘locations’, if no has your server are not sending this property.

---

<div class="post-metadata">

**Author:** ![realjumy](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/realjumy/32/99741_2.png) [@realjumy](https://forum.ionicframework.com/u/realjumy)\
**Post date:** [May 3, 2016, 12:49pm UTC](https://forum.ionicframework.com/t/how-to-handle-nested-json/51056/5 "2016-05-03T12:49:25Z")

</div>

Thanks for the answer.

I can now retrieve the whole information from the JSON. The only thing I can’t do now is to handle that data. I do:

```
> this.locations = [];
> this.locations=data.river.locations;

```

But I think that’s totally wrong, isn’t it? What’s the best way to access to that information?

Thanks.

---

<div class="post-metadata">

**Author:** ![realjumy](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/realjumy/32/99741_2.png) [@realjumy](https://forum.ionicframework.com/u/realjumy)\
**Post date:** [May 3, 2016, 1:04pm UTC](https://forum.ionicframework.com/t/how-to-handle-nested-json/51056/6 "2016-05-03T13:04:26Z")

</div>

I mean, I know how to handle that data from the html view, but what I’m unsure is of how I can transform that data from the js and transform it. I think it is a very basic thing, but I tried without success.

---

<div class="post-metadata">

**Author:** ![sveinla](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/sveinla/32/99969_2.png) [@sveinla](https://forum.ionicframework.com/u/sveinla)\
**Post date:** [May 3, 2016, 1:06pm UTC](https://forum.ionicframework.com/t/how-to-handle-nested-json/51056/7 "2016-05-03T13:06:08Z")

</div>

Are you getting the data ok?  
http.get return an observable so i thought you just couldnt use that directly as the respose i think.

```auto
this.http.get(url).map(res => res.json()).subscribe(res => {
  // Do somethinng with your res
  // Remeber that locations is an array so you have to access it as such
  // res.locations[0].id
});

```

---

<div class="post-metadata">

**Author:** ![sveinla](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/sveinla/32/99969_2.png) [@sveinla](https://forum.ionicframework.com/u/sveinla)\
**Post date:** [May 3, 2016, 1:21pm UTC](https://forum.ionicframework.com/t/how-to-handle-nested-json/51056/8 "2016-05-03T13:21:17Z")

</div>

What you mean by “transform it” ?

---

<div class="post-metadata">

**Author:** ![aaronksaunders](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/aaronksaunders/32/13729_2.png) [@aaronksaunders](https://forum.ionicframework.com/u/aaronksaunders)\
**Post date:** [May 3, 2016, 1:45pm UTC](https://forum.ionicframework.com/t/how-to-handle-nested-json/51056/9 "2016-05-03T13:45:59Z")

</div>

```
import {Component} from '@angular/core';
import {HTTP_PROVIDERS, Http, Headers } from '@angular/http';

// Add all operators to Observable
import 'rxjs/Rx';

@Component({
  selector: 'my-app',
  template: `
    <h1>My First Angular 2 App</h1>
    <div>Here is your data: {{result | json}}</div>
  `,
  providers: [HTTP_PROVIDERS]
})

export class AppComponent { 
  result:any
  
    constructor(http: Http) {
      this.http = http
      this.getData().subscribe(
          (data) => {
            this.result = data
            console.log('item: ', this.result)
            console.log('locations: ', this.result.locations)
          },
          (err) => console.log("Error Loging In: ",err),
          () => { console.log("All Good With The Data") }
        );
    }
  
    getData () {
      return this.http.get("stuff.js")
        .map(res => res.json().item)
  }
}

```

 ![image](https://global.discourse-cdn.com/ionicframework/original/3X/a/5/a587716ac9627d801bc6b947502bd39313d16a50.png)

---

<div class="post-metadata">

**Author:** ![realjumy](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/realjumy/32/99741_2.png) [@realjumy](https://forum.ionicframework.com/u/realjumy)\
**Post date:** [May 3, 2016, 1:59pm UTC](https://forum.ionicframework.com/t/how-to-handle-nested-json/51056/10 "2016-05-03T13:59:58Z")

</div>

Thank you very much for all your answers. And thanks for the example, @aaronksaunders.

@sveinla, what I meant is that I don’t know is what’s the best approach to, for example, select and store only the locations. I was sure that it was something really easy, but I didn’t know how to do it. It is explained in @aaronksaunders’s example.

Again, thank you very much to all of you for your answers.

---

<div class="post-metadata">

**Author:** ![sciu](https://avatars.discourse-cdn.com/v4/letter/s/eb8c5e/32.png) [@sciu](https://forum.ionicframework.com/u/sciu)\
**Post date:** [May 21, 2016, 11:35am UTC](https://forum.ionicframework.com/t/how-to-handle-nested-json/51056/11 "2016-05-21T11:35:47Z")

</div>

Hi @aaronksaunders ,  
Could you help me how to get the token ??  
I am using [backendless.com](http://backendless.com) service.  
My result after succesfull login was like this…

```
Object {lastLogin: 1463742055662, created: 1456890510000, name: "personal", ___class: "Users", user-token: "7652C01C-7343-F9AE-FF15-DD7E0427A800"…}
___class:"Users"
__meta:"{"relationRemovalIds":{},"selectedProperties":["__updated __meta","password","created","name","___ class","ownerId","updated","objectId","email"],"relatedObjects":{}}"
created:1456890510000
email:"personal@gmail.com"
lastLogin:1463742055662
name:"personal"
objectId:"C8FE36A2-9396-13C5-FF9C-8F8EF7F07900"
ownerId:null
updated:null
user-token:"7652C01C-7343-F9AE-FF15-DD7E0427A800"
__proto__ :Object

```

Please look at my console.log at my user\_service.js.  
I can console.log email or objectId but fail for user-token.  
My problem is how to get the user-token and save it to localstorage so i can use it for another purpose??  
my user\_service.js

```
import {Injectable} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Headers, RequestOptions} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import {BackendService} from './backend_service';
import {Storage, LocalStorage, Events} from 'ionic-angular';
import 'rxjs/Rx';

@Injectable()
export class UserService {

    static get parameters() {
        return [[Http], [BackendService], [Events]];
    }

    constructor(http, backendService, events) {
        this.http = http;
        this.backendService = backendService;
        this.events = events;
        this.user = {};
        this.storage = new Storage(LocalStorage);
        this.HAS_LOGGED_IN = 'hasLoggedIn';
        this.Backend_Login_Url = backendService.BackendLoginUrl
        this.Backend_Register_Url = backendService.BackendRegisterUrl
        this.Backend_Logout_Url = backendService.BackendLogoutUrl
        this.Backend_Header = backendService.BackendHeader
    }

   userLogin(userData)
        {
        let body = JSON.stringify({ login: userData.email, password: userData.password });
        let headers = new Headers(this.Backend_Header);
        let options = new RequestOptions({ headers: headers });
        return this.http.post(this.Backend_Login_Url, body, options)
            .map((res) => {
               let data = res.json();
               console.log('data.email at user_service', data.email); // result : personal@gmail.com
               console.log('data.objectId at user_service', data.objectId); // result C8FE36A2-9396-13C5-FF9C-8F8EF7F07900
               console.log('data.user-token at user_service', data.user-token); // result Reference error : Token is not defined
              this.storage.set('userStorage', JSON.stringify(data)); // result : success
              return data;
         });
}

```

Thks in advance.

---

<div class="post-metadata">

**Author:** ![xr0master](https://avatars.discourse-cdn.com/v4/letter/x/b4bc9f/32.png) [@xr0master](https://forum.ionicframework.com/u/xr0master)\
**Post date:** [May 21, 2016, 11:58am UTC](https://forum.ionicframework.com/t/how-to-handle-nested-json/51056/12 "2016-05-21T11:58:46Z")

</div>

> [@SyntaxError: Unexpected token \< in JSON at position 0](https://forum.ionicframework.com/t/syntaxerror-unexpected-token-in-json-at-position-0/49057/10):
>
> You can’t use ‘-’ in variable name. data[‘user-token’]

---

<div class="post-metadata">

**Author:** ![sciu](https://avatars.discourse-cdn.com/v4/letter/s/eb8c5e/32.png) [@sciu](https://forum.ionicframework.com/u/sciu)\
**Post date:** [May 22, 2016, 4:34am UTC](https://forum.ionicframework.com/t/how-to-handle-nested-json/51056/13 "2016-05-22T04:34:48Z")

</div>

Thks @xr0master,

It works now…  
You heal my headache for a couple days…
