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

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

如何將 json gzip 文件解組為結構

如何將 json gzip 文件解組為結構

Go
至尊寶的傳說 2023-06-19 16:07:50
我正在編寫一個 trie DS,將 json gzip 壓縮到一個文件中trieSample.json.gz,然后將其讀回結構中。奇怪的是,解組成功但結構未填充。我試過 json.Unmarshal 和 json.Decoder 都無濟于事。需要幫助找到我在這里缺少的東西。讀取時不會拋出任何錯誤,只是該結構沒有任何鍵。如果我嘗試正常的 json marshal -> 寫入文件并從文件讀取 -> Unmarshal,它會正常工作。var charSet = "0123456789bcdefghjkmnopqrstuvwxyz"const logTagSlice = "trie.log"type trieSlice struct {    Children []*tNode          `json:"c"`    Charset  map[int32]int8    `json:"l"` // Charset is the legend of what charset is used to create the keys and how to position them in trie array    logger   loggingapi.Logger `json:"-"`    capacity int               `json:"-"` // capacity is the slice capacity to have enough to hold all the characters in the charset}type tNode struct {    Children []*tNode `json:"c"`           // children represents the next valid runes AFTER the current one    IsLeaf   bool     `json:"e,omitempty"` // isLeaf represents if this node represents the end of a valid word    Value    int16    `json:"v,omitempty"` // value holds the corresponding value for key value pair, where key is the whole tree of nodes starting from parent representing a valid word}// NewTrieSlice returns a Trie, charset represents how the children need to be positioned in the arrayfunc NewTrieSlice(charset string, logger loggingapi.Logger) *trieSlice {    m := map[int32]int8{}    for index, r := range charset {        m[r] = int8(index)    }    return &trieSlice{        Charset:  m,        Children: make([]*tNode, len(charset)),        logger:   logger,        capacity: len(charset),    }}func newNode(capacity int) *tNode {    return &tNode{        Children: make([]*tNode, capacity),    }}spew.Dump 顯示 trieSlice Children 數組包含所有 nil 元素
查看完整描述

1 回答

?
慕蓋茨4494581

TA貢獻1850條經驗 獲得超11個贊

在使用數據之前關閉壓縮機。使用前先解壓數據。不要因不當使用 bufio.Scanner 而將其砍掉。


var network bytes.Buffer

b, err := json.Marshal(trie)

if err != nil {

    fmt.Println("error in marshal ... ", err.Error())

    t.Fail()

}

w := gzip.NewWriter(&network)

w.Write(b)

w.Close()

err = ioutil.WriteFile("trieSample.json.gz", network.Bytes(), 0644)

if err != nil {

    log.Fatal(err)

}


trieDecoder := NewTrieSlice(charSet)


// attempt via json Unmarshal

file, err := os.Open("trieSample.json.gz")

if err != nil {

    log.Fatal(err)

}

r, err := gzip.NewReader(file)

if err != nil {

    log.Fatal(err)

}

err = json.NewDecoder(r).Decode(trieDecoder)

if err != nil {

    log.Fatal(err)

}

spew.Dump(trieDecoder)

https://play.golang.org/p/pYup3v8-f4c


查看完整回答
反對 回復 2023-06-19
  • 1 回答
  • 0 關注
  • 121 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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