3 回答

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超18個(gè)贊
您可以通過執(zhí)行以下操作來獲取 JSON 結(jié)構(gòu)的頂級(jí)鍵:
package main
import (
"encoding/json"
"fmt"
)
// your JSON structure as a byte slice
var j = []byte(`{"foo":1,"bar":2,"baz":[3,4]}`)
func main() {
// a map container to decode 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("%#v\n", k)
}
請(qǐng)注意,鍵的順序不能與它們?cè)?JSON 結(jié)構(gòu)中的順序相對(duì)應(yīng)。它們?cè)谧罱K切片中的順序甚至在完全相同代碼的不同運(yùn)行之間也會(huì)有所不同。這是因?yàn)榈貓D迭代的工作方式。
- 3 回答
- 0 關(guān)注
- 546 瀏覽
添加回答
舉報(bào)