Home >Backend Development >Golang >How can I access deeply nested JSON keys and values in Go without using custom marshalers and unmarshalers?
Accessing Deeply Nested JSON Keys and Values in Go
Consider the following websocket client code written in Go:
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 }
In this scenario, the error "invalid operation: args[0] (index of type interface {})" arises due to improper notation when accessing the deeply nested "time" key.
Solution
A recommended solution involves utilizing the github.com/bitly/go-simplejson package, which simplifies the navigation of JSON data structures. Refer to the documentation at http://godoc.org/github.com/bitly/go-simplejson for details.
Applying this package to the above code:
// 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 }
Regarding the second part of the original question, declaring a Go struct would necessitate custom marshalers and unmarshalers, which involves implementing the encoding.TextMarshaler and encoding.TextUnmarshaler interfaces. However, using a JSON library like go-simplejson simplifies this process.
The above is the detailed content of How can I access deeply nested JSON keys and values in Go without using custom marshalers and unmarshalers?. For more information, please follow other related articles on the PHP Chinese website!