亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從 Golang 中包含 json 對象列表的文件中讀取單個 json 對象

如何從 Golang 中包含 json 對象列表的文件中讀取單個 json 對象

Go
紅糖糍粑 2023-08-14 14:48:32
[  {   "name" : "abc",   "age" : 10  },  {   "name" : "def",   "age" : 12  }]這是我的 text.json 文件,它有 json 對象數組,所以我想要實現的是從文件中讀取單個對象,而不是使用 golang 讀取整個 json 對象的數組。我不認為 ioutil.ReadAll() 會給我想要的結果。
查看完整描述

2 回答

?
至尊寶的傳說

TA貢獻1789條經驗 獲得超10個贊

希望這能回答您的問題。注釋掉的部分是用于一一解碼所有對象,因此您甚至可以對其進行優化,以便多個 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


查看完整回答
反對 回復 2023-08-14
?
一只甜甜圈

TA貢獻1836條經驗 獲得超5個贊

您可以打開該文件,并使用 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)

       }

   }

}

您需要添加錯誤處理。


查看完整回答
反對 回復 2023-08-14
  • 2 回答
  • 0 關注
  • 230 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號