您可以通过执行以下操作来获取JSON结构的顶级密钥:
package mainimport ( "encoding/json" "fmt")// your JSON structure as a byte slicevar j = []byte(`{"foo":1,"bar":2,"baz":[3,4]}`)func main() { // a map container to depre the JSON structure into c := make(map[string]json.RawMessage) // unmarschal JSON e := json.Unmarshal(j, &c) // panic on error if e != nil { panic(e) } // a string slice to hold the keys k := make([]string, len(c)) // iteration counter i := 0 // copy c's keys into k for s, _ := range c { k[i] = s i++ } // output result to STDOUT fmt.Printf("%#vn", k)}请注意,键的顺序不得与JSON结构中的键顺序相对应。它们在最后一片中的顺序甚至会在完全相同的代码的不同运行之间有所不同。这是由于地图迭代的工作原理。



