1.接口數據格式;前端
{ "code": 0, "isAdmin": true, "data": [{ "id": 2, "ip": "192.168.54.12", "desc": "nginx", "owner": "lops01" }, { "id": 5, "ip": "192.168.77.237", "desc": "運維測試", "owner": "ops02" }, { "id": 6, "ip": "192.168.77.82", "desc": "運維管理", "owner": "ops03" }, { "id": 8, "ip": "192.168.79.230", "desc": "服務檯測試", "owner": "ops04" }, { "id": 9, "ip": "192.168.79.123", "desc": "dev測試", "owner": "ops05" }, { "id": 14, "ip": "192.168.47.107", "desc": "測試ansible封裝", "owner": "ops06" } ], "columns": [{ "name": "id", "alias": "惟一標識" }, { "name": "ip", "alias": "受權IP地址" }, { "name": "desc", "alias": "備註說明" }, { "name": "owner", "alias": "使用方" } ], "message": "success" }
2.go 處理api json 流程;python
(1).導入json,http,io包nginx
(2).定義api 數據結構體;json
(3).發送http請求;api
(4).序列化json對象轉爲定義結構體;數據結構
(5).輸出轉化json結果;運維
3.處理實例實際代碼;ide
package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" ) //定義api接口數據結構和序列化json字段 type Data struct { ID int `json:"id"` IP string `json:"IP"` DESC string `json:"desc"` OWNER string `json:"owner"` } type CloumnsData struct { NAME string `json:"name"` ALIAS string `json:"alias"` } type Employee struct { CODE int `json:"code"` ISADMIN bool `json:"isadmin"` DATA []Data `json:"data"` COLUMNS []CloumnsData `json:"columns"` MESSGAE string `json:"messgae"` } //發送http請求和json 序列化並打印數據結構; func main() { url := "http://ops-environment.com/channel/ip/v1" resp, _ := http.Get(url) s := Employee{} body, _ := ioutil.ReadAll(resp.Body) resp.Body.Close() json.Unmarshal([]byte(body), &s) fmt.Println(fmt.Sprintf("%+v",s)) }
4.api 執行處理結果;測試
{CODE:0 ISADMIN:true DATA:[{ID:2 IP:192.168.54.12 DESC:nginx OWNER:ops01} {ID:5 IP:192.168.77.237 DESC:運維測試 OWNER:ops02} {ID:6 IP:192.168.77.82 DESC:運維管理 OWNER:ops03} {ID:8 IP:192.168.79.230 DESC:服務檯測試 OWNER:ops04} {ID:9 IP:192.168.79.123 DESC:dev測試 OWNER:ops05} {ID:14 IP:192.168.47.107 DESC:測試ansible前端封裝 OWNER:ops06}] COLUMNS:[{NAME:id ALIAS:惟一標識} {NAME:ip ALIAS:受權IP地址} {NAME:desc ALIAS:備註說明} {NAME:owner ALIAS:使用方}] MESSGAE:}