如何在不使用自訂編組器和解組器的情況下存取 Go 中深度嵌套的 JSON 鍵和值?
Oct 26, 2024 pm 07:41 PM在Go 中訪問深度嵌套的JSON 鍵和值
考慮以下用Go 編寫的websocket 客戶端程式碼:
import ( "encoding/json" "log" ) func main() { msg := `{"args":[{"time":"2013-05-21 16:56:16", "tzs":[{"name":"GMT"}]}],"name":"send:time"}` var u map[string]interface{} err := json.Unmarshal([]byte(msg), &u) if err != nil { log.Fatalf("Failed to unmarshal: %v\n", err) } args := u["args"] // Attempting to directly access the time key will throw an error log.Println(args[0]["time"]) // invalid notation }
登入後複製
在這種情況下,由於存取深度嵌套的「time」鍵時的表示法不正確,會出現「無效操作:args[0] (index of type interface {})」錯誤。
解決方案
推薦的解決方案涉及利用github.com/bitly/go-simplejson 包,它簡化了JSON 資料結構的bitly/go-simplejson
包,它簡化了JSON 資料結構的導航。詳細資訊請參閱 http://godoc.org/github.com/bitly/go-simplejson 的文件。 將此套件應用於上述程式碼:// Import go-simplejson import "github.com/bitly/go-simplejson" func main() { // Create a JSON object json := simplejson.New() json.Decode([]byte(msg)) // Using go-simplejson, access the time key time, err := json.Get("args").GetIndex(0).String("time") if err != nil { log.Fatalf("Failed to get time: %v\n", err) } log.Println(time) // Returns the time value }
登入後複製
以上是如何在不使用自訂編組器和解組器的情況下存取 Go 中深度嵌套的 JSON 鍵和值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱門文章
擊敗分裂小說需要多長時間?
3 週前
By DDD
倉庫:如何復興隊友
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 週前
By 尊渡假赌尊渡假赌尊渡假赌
公眾號網頁更新緩存難題:如何避免版本更新後舊緩存影響用戶體驗?
3 週前
By 王林

熱門文章
擊敗分裂小說需要多長時間?
3 週前
By DDD
倉庫:如何復興隊友
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 週前
By 尊渡假赌尊渡假赌尊渡假赌
公眾號網頁更新緩存難題:如何避免版本更新後舊緩存影響用戶體驗?
3 週前
By 王林

熱門文章標籤

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)