Go语言动态解析JSON,及动态添加Array

代码
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)
         }
      }
   }
}

郝先生

继续阅读此作者的更多文章