3

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?

shubham
  • 39
  • 1
  • 4
  • from the above code not getting that what exactly you are doing explain it more – Soumya B. Athani Jan 03 '19 at 05:05
  • In the http.get one does not need to call map anymore as it returns a json already. Thus I used the code below. `this.http.get('assets/csvjson.json') .subscribe(data => { data.forEach((item) => { console.log(item); console.log(item.Category);` – shubham Jan 09 '19 at 21:45

4 Answers4

2

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);
manish kumar
  • 4,412
  • 4
  • 34
  • 51
1

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
            });
    }```
Masciuniria
  • 174
  • 1
  • 3
  • 10
0

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);
}
Jonathan
  • 330
  • 2
  • 12
  • 1
    You may need to modify your typescript configuration to use this solution, see: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html#new---resolvejsonmodule, and https://stackoverflow.com/questions/49996456/importing-json-file-in-typescript – Sébastien May 30 '20 at 18:39
0

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

constructor(private http: HttpClient) { }

this.http.get("assets.data.json").subscribe((data:any)=>{
  console.log(data);
});
Joe
  • 811
  • 1
  • 8
  • 14