In Python, it's straightforward to extract a single value from a JSON object without defining a struct. Go, on the other hand, requires declaring a struct to represent the expected JSON structure. However, this approach may seem cumbersome for obtaining just a specific value.
Instead of creating a dedicated struct, you can leverage the standard json package to decode JSON into a map[string]interface{}. This allows you to access the value by key:
import ( "encoding/json" "fmt" ) func main() { b := []byte(`{"ask_price":"1.0"}`) data := make(map[string]interface{}) err := json.Unmarshal(b, &data) if err != nil { panic(err) } if price, ok := data["ask_price"].(string); ok { fmt.Println(price) } else { panic("wrong type") } }
Maps provide flexibility as they allow you to:
Structs remain useful for:
The decision between maps and structs depends on the specific requirements of your application. If you prioritize simplicity and flexibility, maps might be a better choice. If type safety and explicit data representation are essential, structs are recommended.
The above is the detailed content of How Can I Efficiently Extract a Single Value from JSON in Go Without Defining a Struct?. For more information, please follow other related articles on the PHP Chinese website!