I am struggling to find an npm package or create my own function that can generate a JSON file from elements within this specific class:
export class TranslatedFileElement {
private key: string
private hasChild: boolean
private value?: string
private values?: TranslatedFileElement[]
private isTranslated?: boolean
public constructor() {
this.key = '',
this.hasChild = false,
this.value = '',
this.values = null,
this.isTranslated = false
}
public setTranslateFileElement(
_key: string,
_value: string,
_values: TranslatedFileElement[],
_hasChild: boolean,
_isTranslated: boolean
) {
this.key = _key
this.value = _value
this.values = _values
this.hasChild = _hasChild,
this.isTranslated = _isTranslated
}
public setKey(_key: string) {
this.key = _key
}
[...] //Other get's and set's
}
I have attempted a solution similar to the following code snippet, but it is not functioning correctly and seems to be causing more issues than solving:
private converter(elementsToJSON: TranslatedFileElement[], nestedLevel: number = 0): string {
let JSONResult = '{'
elementsToJSON.forEach((element) => {
JSONResult = JSONResult + '"' + element.getKey() + '" : '
if (element.getHasChild()) {
JSONResult = JSONResult +
this.converter(element.getValues(), nestedLevel + 2)
} else {
JSONResult = JSONResult + '"' + element.getValue() + '",'
}
})
JSONResult = JSONResult + '},'
JSONResult = JSON.parse(JSON.stringify(JSONResult));
return JSONResult
}
Does anyone know of a reliable npm package or have a simple idea to help me solve this issue?