Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

properly import default export from JSON module

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.

like image 566
Normunds Kalnberzins Avatar asked Oct 16 '25 06:10

Normunds Kalnberzins


1 Answers

You need add allowSyntheticDefaultImports in your tsconfig.json.

tsconfig.json

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

TS

import countries from './countries/es.json';
like image 186
Hsuan Lee Avatar answered Oct 18 '25 20:10

Hsuan Lee