在Go Lang

时间:2019-05-20 18:23:37

标签: json csv go struct

寻找在保留层次结构的同时将JSON读取结构导出为csv格式的想法。

https://play.golang.org/p/jf2DRL1hC5K

/* 
Expected output in excel for data wrangling: 
A Key       | B Key     | C Key     | D Key
SomethingA    SomethingB      SomethingC      SomethingF 
SomethingA    SomethingB      SomethingC      SomethingG
SomethingA    SomethingB      SomethingC      [1,2,3]   
*/

我尝试如下遍历该结构

for _, value := range mymodel { 
   fmt.Println(value) 

/* could not iterate over structs */ 
} 

1 个答案:

答案 0 :(得分:1)

在RootModel中为标头和单独的行添加一个方法(因此您可以在类型范围内,并且仅将标头打印一次):

type RootModel struct {
        A string
        B string
        C string
        D factors
}

type factors struct {
        F string
        G string
        H []int
}

func (*RootModel) CSVheader(w io.Writer) {
        cw := csv.NewWriter(w)
        cw.Write([]string{"A Key", "B Key", "C Key", "D Key"})
        cw.Flush()
}

func (rm *RootModel) CSVrow(w io.Writer) {
        cw := csv.NewWriter(w)
        cw.Write([]string{rm.A, rm.B, rm.C, rm.D.F})
        cw.Write([]string{rm.A, rm.B, rm.C, rm.D.G})

        is, _ := json.Marshal(rm.D.H)
        cw.Write([]string{rm.A, rm.B, rm.C, string(is)})
        cw.Flush()
}

游乐场:https://play.golang.org/p/c8UQVQ8tQTX

输出:

A Key,B Key,C Key,D Key
SomethingA,SomethingB,SomethingC,SomethingF
SomethingA,SomethingB,SomethingC,SomethingG
SomethingA,SomethingB,SomethingC,"[1,2,3]"

注意:如果您要处理RootModel的一部分,则可能希望将CSV编写器逻辑放在该级别上,以便它可以处理标头的单个呈现器-行,然后是随后的数据行。