【问题标题】:How to read a single json object from a file having list of json objects in Golang如何从具有Golang中json对象列表的文件中读取单个json对象
【发布时间】:2019-12-12 05:13:06
【问题描述】:
[
  {
   "name" : "abc",
   "age" : 10
  },
  {
   "name" : "def",
   "age" : 12
  }
]

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

【问题讨论】:

    标签: json go unmarshalling


    【解决方案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
    

    【讨论】:

    【解决方案2】:

    您可以打开文件,然后使用 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 对象,但是一个接一个?
    • 是的,我在答案中添加了这个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 2019-11-25
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    相关资源
    最近更新 更多