Go Lang中的JSON结构到csv
正在寻找将JSON读取结构导出为某种csv格式,同时保留层次结构的想法 我已经尝试了如下迭代结构Go Lang中的JSON结构到csv,json,csv,go,struct,Json,Csv,Go,Struct,正在寻找将JSON读取结构导出为某种csv格式,同时保留层次结构的想法 我已经尝试了如下迭代结构 for _, value := range mymodel { fmt.Println(value) /* could not iterate over structs */ } 向RootModel中添加标题和单行的方法(这样您就可以在类型范围内,只打印一次标题): 游乐场: 输出: A Key,B Key,C Key,D Key SomethingA,SomethingB,S
for _, value := range mymodel {
fmt.Println(value)
/* could not iterate over structs */
}
向RootModel中添加标题和单行的方法(这样您就可以在类型范围内,只打印一次标题): 游乐场: 输出:
A Key,B Key,C Key,D Key
SomethingA,SomethingB,SomethingC,SomethingF
SomethingA,SomethingB,SomethingC,SomethingG
SomethingA,SomethingB,SomethingC,"[1,2,3]"
注意:如果您处理的是
RootModel
的一部分,您可能希望将CSV编写器逻辑置于该级别,这样它就可以处理标题行的单个呈现,然后是后续数据行。如果我使用该格式,这看起来不错,但我的格式实际上是在一个结构中。我已经阅读了csv包,我知道如果我有预期格式的数据,这可能是一个输出-如上面的“预期输出”所示,但我的数据都是结构格式。{SomethingA SomethingB SomethingC{SomethingF SomethingG[1 2 3]},我该如何格式化这个into@superenme更新了答案,包括struct方法,以实现单个或多个记录输出的预期结果。我找到了另一种方法,因为我有许多根模型,或者我可以迭代根模型的[]数组。我可以迭代数组而不是结构。非常感谢您的回答,这肯定也有帮助!
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()
}
A Key,B Key,C Key,D Key
SomethingA,SomethingB,SomethingC,SomethingF
SomethingA,SomethingB,SomethingC,SomethingG
SomethingA,SomethingB,SomethingC,"[1,2,3]"