本人也从事了接近2年的Go语言开发,其中Go对动态解析Json和动态添加数组内容不是特别方便,下面就把一些操作例子分享一下:
代码(有注释)
package main
import (
"log"
"encoding/json"
)
func main() {
//可变标准map
mp := make(map[int]interface{})
for i := 1; i <= 100; i++ {
mp[i] = 1
}
log.Print(mp)
//map转json
jsonString, err := json.Marshal(mp)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(jsonString))
//动态添加数组
var sl []int
for j := 1; j <= 10000; j++ {
sl = append(sl, j)
}
log.Print(sl)
//动态解析json
js := `{"code":1,"t":"2","b":[2,3,4,"abc"]}`
var jsMap map[string]interface{}
e := json.Unmarshal([]byte(js), &jsMap)
if e != nil {
log.Print(e)
}
for k, v := range jsMap {
log.Print(k)
log.Print(v)
if k == "b" {
for _, vv := range v.([]interface{}) {
log.Print(vv)
}
}
}
}