簡體   English   中英

如何從 Typescript 中的鍵值自定義 class 生成 JSON 文件

[英]How to generate JSON file from key - value custom class in Typescript

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
}

我嘗試過這樣的事情,但它不能正常工作並且產生的問題比解決的問題更多:

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
  }

有人知道好的 npm (未棄用) package 這樣做還是有想法簡單地解決它?

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};
    }
...
}

你能做的就是打電話

JSON.stringify(elementsToJSON);

class 屬性將轉換為 JSON。

唯一的問題是如果您的數據結構不是樹並且其中有循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM