寻找想法将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 */
}
最佳答案
在您的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编写器逻辑放在该级别上-这样它就可以处理标头行的单个渲染,然后处理后续的数据行。关于json - JSON结构到Go Lang中的csv,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56226275/