Ionic read local JSON file

Viewed 6050

I am trying to read a local JSON file in Ionic 3. I have saved the JSON file in assets folder as csvjson.json

I call the following function inside one of the services.

getProducts() { console.log('Inside getProducts')

return this.http.get(this.apiHost)
  .map((response: Response) => {
    console.log(response);
    return response.json();
  });

}

and then store the result in

myArray = this.databaseprovider.getProducts();
console.log("Returned from getProducts:" + myArray.length);

However I get the output as

Returned from getProducts:undefined

Can you pls suggest where I am going wrong?

4 Answers

Put the <file-name>.json file in assets folder and change the request to following,

public getProducts() { 
    return new Promise((resolve, reject) => {
        this._http.get("assets/<file-name>.json")
            .map((response: Response) => {
                console.log(response);
                resolve(response.json());
        });
    });
}

Component file

this.databaseprovider.getProducts().then((result)=>{
   myArray = result;
});
console.log("Returned from getProducts:" + myArray.length);

The easiest way is to use fetch() function like that:

    readJsonData(){    
            fetch("../../assets/data/Parameters.json").then(res=>res.json()).then(json=>{
                console.log("OUTPUT: ", json);
                //DO YOUR STAFF
            });
    }```

When you call it in your Typescript File of your Page for example called yourPage.ts in the yourPage folder you can access the local JSON File by importing it:

yourPage.ts:

import * as JSONdata from "../../assets/csvjson.json" //You can name 'JSONdata' as you want

To call it:

getProducts() {
 console.log(JSONdata);
}

import { HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) { }

this.http.get("assets.data.json").subscribe((data:any)=>{
  console.log(data);
});
Related