gpt4 book ai didi

json - 你如何使用 go-simplejson 遍历 json 文件

转载 作者:IT王子 更新时间:2023-10-29 01:06:42 27 4
gpt4 key购买 nike

我有一个 JSON 格式的文件:

{
"data": {
"docs": [
{"key00": "val00", "key01": "val01"},
{"key10": "val10", "key11": "val11"}
]
}
}

我想将其转换为单独的 JSON 文档:

文件0.json

{
{"key00": "val00", "key01": "val01"}
}

文件1.json

{
{"key10": "val10", "key11": "val11"}
}

我可以使用以下方法枚举数组内容:

j, _ := ioutil.ReadFile(path)
dec, _ := simplejson.NewFromReader(bytes.NewReader(j))
for i,v := range dec.Get("data").Get("docs").MustArray() {
out := simplejson.New()

/* ??? move dec key/value pairs to out ??? */

b, _ := out.EncodePretty()
ioutil.WriteFile(outpath, b, 0777)
}

但我不确定如何遍历数组条目中的键/值对。这是一个不错、简洁的库,但似乎没有很多示例,而且我的 golang 专业知识目前有限。

任何帮助将不胜感激..谢谢!

最佳答案

您可以使用 simplejson.Set :

for _, doc := range dec.Get("data").Get("docs").MustArray() {
out := simplejson.New()
// doc is an interface{} holding a map, we have to type assert it.
for k, v := range doc.(map[string]interface{}) {
out.Set(k, v)
}
b, _ := out.EncodePretty()
fmt.Printf("%s\n", b)
}

但是在那种情况下,simplejson 是一种矫枉过正的做法,使用 struct/stdlib 效率更高。

为了完整起见,标准库版本:

type DataLayout struct {
Data struct {
Docs []map[string]string `json:"docs"`
} `json:"data"`
}

func main() {
var in DataLayout
err := json.NewDecoder(strings.NewReader(j)).Decode(&in)
if err != nil {
log.Fatal(err)
}
for _, doc := range in.Data.Docs {
b, err := json.MarshalIndent(doc, "", "\t")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", b)
}
}

play

注意事项:

  • 您的 json 示例是错误的,"key10", "val10" 应该是 "key10": "val10"
  • 当您不确定数据结构的外观并且懒得阅读代码时,请使用 fmt.Printf("%#v", doc) 查看它的外观。

关于json - 你如何使用 go-simplejson 遍历 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28643877/

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