properly import default export from JSON module

Viewed 1013

I have a JSON translation file "./countries/es.json" in my Angular application that I want to import and loop through.

{
...
"Solomon Islands": "Islas Salomón",
"South Sudan": "Sudán del Sur",
...
}

I have "resolveJsonModule": true, in my tsconfig.json file, so in general import goes well.

import * as countries from './countries/es.json';

and if I access the object say countries['Solomon Islands'] I get 'Islas Salomón' that is correct.

However if want to enumerate all countries:

const countries_keys = Object.keys(countries);

countries_keys is an array with one value 'default'. In order to obtain the country list I need to do:

const countries_keys = Object.keys(countries['default']);

My question - is there a way to do the import cleanly so I get the object exactly as in JSON file?

If I had the source file like:

{
countries: {
    ...
    "Solomon Islands": "Islas Salomón",
    "South Sudan": "Sudán del Sur",
    ...
    }
}

I could simply do:

import  { countries } from './countries/es.json';

but is there a clean way to import my original file as equivalent JSON object without the additional 'default' property.

3 Answers

import is not a good idea here later on if you want to move your file to some server you will need to rewrite the whole logic i would suggest to use httpclient get call here.So move you file to assets folder and then

constructor(private http:HttpClient){
this.http.get('assets/yourfilepath').subscribe(data=>{
   const countries_keys = Object.keys(data['countries']);
   console.log(data['countries'])//data is your json object here
})
}

You need add allowSyntheticDefaultImports in your tsconfig.json.

tsconfig.json

{
  "allowSyntheticDefaultImports": true,
  "resolveJsonModule": true
}

TS

import countries from './countries/es.json';

What worked form me was:

import countries from './countries/es.json';

This is the "default import"

Related