I have issues with finding npm package or creating own function to generate json file from elements in this class:
export class TranslatedFileElement {
private key: string
private hasChild: boolean // True if vaule is empty, vaules not empty; False if value not empty, values is empty
private value?: string // One of them should be required, because if TranslatedFileElement have any childs,
private values?: TranslatedFileElement[] // then value should be empty, if not, values should be empty
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 tried something like this, but it not working properly and generating more problems 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
}
Somebody know good npm (not deprecated) package to do this or have idea to simply solve it?
I would suggest adding a method that would translate this structure to an object that has same structure as json that you want and calling JSON.stringify on object thusly created.
class TranslatedFileElement {
...
public toJSON(){
return JSON.stringify(this.toObject());
}
public toObject(){
let val:any=null;
if (this.hasChild){
const reducer = (acc:any, val:any) => ({...acc,...val});
if (this.values)
val = this.values.map((child:TranslatedFileElement)=>child.toObject()).reduce(reducer,{});
}else{
val = this.value;
}
return {[this.key]:val};
}
...
}
What you can do is simply call
JSON.stringify(elementsToJSON);
The class properties will get translated into JSON.
Only problem would be if The structure of your data is not a tree and has cycles in it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.