第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何從 Golang 中包含 json 對(duì)象列表的文件中讀取單個(gè) json 對(duì)象

如何從 Golang 中包含 json 對(duì)象列表的文件中讀取單個(gè) json 對(duì)象

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

2 回答

?
至尊寶的傳說

TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超10個(gè)贊

希望這能回答您的問題。注釋掉的部分是用于一一解碼所有對(duì)象,因此您甚至可以對(duì)其進(jìn)行優(yōu)化,以便多個(gè) goroutine 可以同時(shí)進(jìn)行解碼。


包主


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


查看完整回答
反對(duì) 回復(fù) 2023-08-14
?
一只甜甜圈

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超5個(gè)贊

您可以打開該文件,并使用 json.Decoder 開始讀取該文件。讀取數(shù)組第一個(gè)元素的代碼草圖如下所示:


decoder:=json.NewDecoder(f)

t,err:=decoder.Token()

tok, ok:=t.(json.Delim) 

if ok {

   if tok=='[' {

       for decoder.More() {

         decoder.Decode(&oneEntry)

       }

   }

}

您需要添加錯(cuò)誤處理。


查看完整回答
反對(duì) 回復(fù) 2023-08-14
  • 2 回答
  • 0 關(guān)注
  • 224 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)