首頁  >  文章  >  後端開發  >  如何在不使用自訂編組器和解組器的情況下存取 Go 中深度嵌套的 JSON 鍵和值?

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

DDD
DDD原創
2024-10-26 19:41:02412瀏覽

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn