'Is there a way to read a JSON-File using a String in TypeScript?
I'm doing the frontend for a project im working in with a friend and I am struggeling with the language-switch at the moment.
I planned to make a function, which I can call with an Attribute 'id' to read a text from a JSON-File (See pictures bellow for better info). However im struggeling here, because obveously I cant just return data.id. I can't find something on the internet and was wondering if someone here could help me.
Goal is, that I can call t(navigation.xyz) from any point in the applicationand will receive the right text.
import * as dataEn from "./en.json";
import * as dataDe from "./de.json";
import {ELanguage} from "../enums/OGFE-Enums";
function t(id: string): string {
let language: ELanguage = ELanguage.ENGLISH;
id = "navigation.games";
if (language === ELanguage.ENGLISH) {
return dataEn?.;
} else {
return dataDe.id;
}
}
JSON:
{
"navigation": {
"games": "Games",
"about-us": "About us",
"installation-guide": "Installation Guide",
"release-notes": "Release notes",
"qaa": "Q&A"
}
}
Solution 1:[1]
One workaround is to keep your json in a .js file and export as a const like this:
dataEn.js
export dataEn
{
// your json here...
}
and then import it as:
import dataEn from '../dataEn.js'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Devesh |
