简体   繁体   中英

ionic 3 - Extract data from nested JSON into an array

So i am having problems trying to parse a json file to store it into an array.

Here is the api site that I am parsing my JSON from: https://data.gov.sg/api/action/datastore_search?resource_id=139a3035-e624-4f56-b63f-89ae28d4ae4c&limit=5

Downloading the file is successful, but the problem now is to parse it's contents into an array as everytime I tried to view the contents through console.log() , i keep getting [object Object] in return. My goal is to store the contents of result/records in the json into an array and return it to the parent method

Am I doing something wrong somewhere?

Here is my code:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class CarparkInfoService {

  constructor(public http: HttpClient) {
    console.log('Carpark Info Service Provider');
  }
  getCarparkData(): Observable<any> {
    let data1: Observable<any>;
    data1 = this.http.get('https://data.gov.sg/api/action/datastore_search?resource_id=139a3035-e624-4f56-b63f-89ae28d4ae4c&limit=5');
    console.log("data=" + data1); // Returns [object Object]
    return data1;
  }
}

So the issue is that you want to see your json data while it is not even pulled from the service since what you console log is an observable:

// this below returns observable

getCarparkData(): Observable<any> {
    let data1: Observable<any>;
    data1 = this.http.get('https://data.gov.sg/api/action/datastore_search?resource_id=139a3035-e624-4f56-b63f-89ae28d4ae4c&limit=5');
    console.log("data=" + data1); // Returns [object Object]
    return data1;
}

So to get and parse data you need to subscribe to this observable which will call this api once:

getJson() {
    this.getCarparkData().subscribe( data => { 
        console.log(data)
        // here you can work with your json
    }
}

So make sure you subscribe to your observable which will “activate” the call to API

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM