How to direct access a value of JSON return array


#1

Dears;
fallowing code return item field of JSON contains a single “str” field:

json file: {"next":{"$ref":"http://80.75.3.205:8080/.../.../getudi"},"items":[{"str":"D0YTW6NTR4S6WGWUXF0O"}]}

load(){
return new Promise(resolve =>		
		this.http.get('http://80.75.3.205:8080/.../.../getudi')
		.map(res => res.json())
		.subscribe(data => {
  		this.data = data.items;
  		//console.log(this.data);
  		resolve(this.data);
		}));
}

how can I return only str value.


#2
this.data = data.items[0].str;
resolve(this.data);

#3

Dear anatolys, thank you so much for your guiding, I dont’t know so much about coding.
Thanks


#4

This code is extremely baroque.

load(): Observable<string> {
  return this.http.get(url).map((rsp) => {
    // it would be best here if you had an actual interface type for what is coming from the server to make typos harder
    return rsp.json().items[0].str;
  });
}

I’m deliberately not setting this.data here, because virtually always you don’t really want to do that, as you will get subtle bugs with stale data. If you are going to do it, don’t make it a simple value. Make it a ReplaySubject and do this:

load() {
  let req = this.http.get(url).map((rsp) => {
    return rsp.json().items[0].str;
  });
  req.subscribe((newstr) => {
   this.data.next(newstr);
  }
  return req;
}

…and in this idiom, you probably don’t even want to be returning anything from load(), because everybody who’s interested in the value should be subscribing to the data Subject, which will be automatically updated. load() then becomes simply a trigger to update data.


#5

Thank you so much Rapropos,
It seems this code is more robust and stronger structure but also for me looking some complex to understand. :pensive:


#6

If for any reasons webservice changed and return a none json data, for example only str value so how we can get it?