如何在Golang中从一个有json对象列表的文件中读取一个json对象。

问题描述 投票:-2回答:2
[
  {
   "name" : "abc",
   "age" : 10
  },
  {
   "name" : "def",
   "age" : 12
  }
]

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

json go unmarshalling
2个回答
1
投票

你可以打开这个文件,然后使用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)
       }
   }
}

你需要添加错误处理。


1
投票

希望这能回答你的问题。注释出来的部分是用来逐个解码所有对象的,因此你甚至可以优化它,使多个goroutine可以并发地进行解码。

包主

import (
    "encoding/json"
    "fmt"
    "log"
    "os"
)

type jsonStore struct {
    Name string
    Age  int
}

func main() {
    file, err := os.Open("text.json")
    if err != nil {
        log.Println("Can't read file")
    }
    defer file.Close()

    // NewDecoder that reads from file (Recommended when handling big files)
    // It doesn't keeps the whole in memory, and hence use less resources
    decoder := json.NewDecoder(file)
    var data jsonStore

    // Reads the array open bracket
    decoder.Token()

    // Decode reads the next JSON-encoded value from its input and stores it
    decoder.Decode(&data)

    // Prints the first single JSON object
    fmt.Printf("Name: %#v, Age: %#v\n", data.Name, data.Age)

    /*
        // If you want to read all the objects one by one
        var dataArr []jsonStore

        // Reads the array open bracket
        decoder.Token()

        // Appends decoded object to dataArr until every object gets parsed
        for decoder.More() {
            decoder.Decode(&data)
            dataArr = append(dataArr, data)
        }
    */
}

产量

Name: "abc", Age: 10
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.