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.
You need add allowSyntheticDefaultImports
in your tsconfig.json
.
tsconfig.json
{
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true
}
TS
import countries from './countries/es.json';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With