@

1. 通过结构体映射解析

原数据结构


解析

// 结构体
type contractJson struct {
 Data  []transaction `json:"data"`
 Total int           `json:"total"`
}
// data下的数组
type transaction struct {
 Result       string `json:"result"`
 OwnerAddress string `json:"ownerAddress"`
}


  // rs是http请求返回的数据
  rs := string(body)
  if rs == "" {
   return nil
  }

  contractJson1 := contractJson{}
  err := json.Unmarshal([]byte(rs), &contractJson1)
  if err != nil {
   log.Fatal(err)
  }
  fmt.Println(contractJson1.Data[1])

2. 嵌套json解析-map

// http请求返回的json数据
result := SendHttp(urls, method, rawurl, cookie)
 fmt.Println(result)

 // 定义make(map[string]interface{})
 r := make(map[string]interface{})
 fmt.Println([]byte(result))
 // 调用标准库encoding/json的Unmarshal
 // 将JSON数据(JSON以字符串形式表示)转换成[]byte,并将数据加载到对象r的内存地址
 json.Unmarshal([]byte(result), &r)
 // r["data"]是读取JSON最外层的key
 // 如果嵌套JSON数据,则使用map[string]interface{}读取下一层的JSON数据
 // 如读取key为data里面嵌套的result:r["data"].(map[string]interface{})["result"]
 // 如果JSON的某个key的数据以数组表示,则使用([]interface{})[index]读取数组中某个数据。
 // 如读取key为result的第四个数据:r["data"].(map[string]interface{})["result"].([]interface{})[3]
 fmt.Println(r["data"].(map[string]interface{})["result"].([]interface{})[3])