Getting local JSON data

Hello, I am trying to load a local JSON file located in the assets folder.

 this.http.get('assets/data.json', {}, {})
      .then(data => {
        let returnJson = JSON.parse(data.data);
        this.items = returnJson;
      }).catch((error) => {
        this.error_msg = error.error;
      });

It keeps triggering the catch: There was an error with the request

Thanks!

I think you need ionic file plugin to access the contents of file placed in assets folder.

this.file.readAsText(this.file.applicationDirectory + "www/assets", "data.json").then(...)

This should work.

This my code for getting json data from a file in a sub folder of assets called data and the file named subtitles.json

this.http.get('assets/data/subtitles.json').map(res => res.json()).subscribe(data => {
               this.subtitles = data;
          });
8 Likes

How can i read local json file with the ionic native HTTP plugin(not angular http)?

why do you want to use the native ionic http plugin? That plugin might not have access to the internal files.

Because I have no access to backend and I can not enable cors on it, because of that, the new webkview on ios not pass http request across domains with the angular http client

Works on web, but when running an apk I get

XMLHttpRequest cannot load file:///android_asset/www/assets/mocks/category.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, https.s 
HttpErrorResponse

try require/importing it - just a thought, but it should work

Better use the fetch() function than http.get:

            fetch("../../assets/data/Parameters.json").then(res=>res.json()).then(json=>{                
                //DO YOUR STAFF
            });