package main
import (
"fmt"
"encoding/json"
)
func main() {
// Create a map to parse the JSON
var data map[string]interface{}
// Define a JSON string
j := `{"key":"value"}`
// Parse our JSON string
err := json.Unmarshal([]byte(j), &data)
if err != nil {
fmt.Println("Error parsing JSON string:", err)
}
// check if a key exist?
if val, ok := data["key"]; ok {
fmt.Println(val)
} else {
fmt.Println("not exist")
}
}
运行结果:
$ go run e.go
value
参考
https://bencane.com/2020/12/08/maps-vs-structs-for-json/
https://stackoverflow.com/questions/2050391/how-to-check-if-a-map-contains-a-key-in-go