gpt4 book ai didi

Go Lang 中的 JSON 结构到 csv

转载 作者:数据小太阳 更新时间:2023-10-29 03:40:26 25 4
gpt4 key购买 nike

寻找在保留层次结构的同时将 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()
}

Playground :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 的 slice ,您可能希望将 CSV 编写器逻辑放在该级别 - 这样它就可以处理单个渲染标题行,然后是后续数据行。

关于Go Lang 中的 JSON 结构到 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56226275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com