How to handle nested JSON

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.

Hi!

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

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

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.

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.

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.

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.

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
});

What you mean by “transform it” ?

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

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.

Hi @aaronksaunders ,
Could you help me how to get the token ??
I am using 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.

Thks @xr0master,

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