[
{
"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/