gpt4 book ai didi

json - 如何从Golang中具有json对象列表的文件中读取单个json对象

转载 作者:行者123 更新时间:2023-12-01 22:38:50 25 4
gpt4 key购买 nike

[
{
"name" : "abc",
"age" : 10
},
{
"name" : "def",
"age" : 12
}
]

所以这是我的text.json文件,它具有json对象数组,所以我要实现的是从文件中读取单个对象,而不是使用golang读取整个​​json对象的数组。我认为ioutil.ReadAll()不会给我想要的结果。

最佳答案

您可以打开文件,然后使用json.Decoder开始读取文件。读取数组第一个元素的代码草图如下所示:

decoder:=json.NewDecoder(f)
t,err:=decoder.Token()
tok, ok:=t.(json.Delim)
if ok {
if tok=='[' {
for decoder.More() {
decoder.Decode(&oneEntry)
}
}
}

您需要添加错误处理。

关于json - 如何从Golang中具有json对象列表的文件中读取单个json对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59298089/

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