首頁 > 後端開發 > Golang > 主體

如何在不使用自訂編組器和解組器的情況下存取 Go 中深度嵌套的 JSON 鍵和值?

DDD
發布: 2024-10-26 19:41:02
原創
411 人瀏覽過

How can I access deeply nested JSON keys and values in Go without using custom marshalers and unmarshalers?

在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 結構體需要自訂編組器和解組器,其中涉及實作encoding.TextMarshaler和encoding.TextUnmarshaler 介面。然而,使用像 go-simplejson 這樣的 JSON 函式庫可以簡化這個過程。

以上是如何在不使用自訂編組器和解組器的情況下存取 Go 中深度嵌套的 JSON 鍵和值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!