golang学习之html json解析
发布时间:2020-12-16 18:44:26 所属栏目:大数据 来源:网络整理
导读:golang解析html文件 由于项目中需要用到json,使用的是https://github.com/bitly/go-simplejson.git 下载到配置的gopath路径的src下面 连接的地址是: "http://lengxiaohua.com/lengxiaohuaapi/joke?action=getJokesinterval=weeklysort=populartype=text%7C
golang解析html文件 由于项目中需要用到json,使用的是https://github.com/bitly/go-simplejson.git 下载到配置的&gopath路径的src下面
连接的地址是: "http://lengxiaohua.com/lengxiaohuaapi/joke?action=getJokes&interval=weekly&sort=popular&type=text%7Cimage&start=0&limit=20"
步骤很简单 1.连接url获取页面内容 2.将页面内容转换成json 3.解析json,打印到控制台
代码很简单如下,直接运行就可以 </pre><pre name="code" class="cpp">// TestGoCommand project main.go package main import ( "encoding/json" "fmt" "go-simplejson" // for json get //"gopkg.in/mgo.v2" //"gopkg.in/mgo.v2/bson" "io/ioutil" "net/http" //"regexp" //"strconv" ) func Get(url string) (content string,statusCode int) { resp,err1 := http.Get(url) if err1 != nil { statusCode = -100 return } defer resp.Body.Close() data,err2 := ioutil.ReadAll(resp.Body) if err2 != nil { statusCode = -200 return } js,err := simplejson.NewJson(data) if err != nil { panic(err.Error()) } weilist := []weidata{}[:] for _,v := range js.Get("jokes").MustArray() { prase(v) //append(weilist,prase(v)) //fmt.Println(i,v) } fmt.Print(weilist) statusCode = resp.StatusCode content = string(data) return } /**interface的强制类型转换**/ func prase(m1 interface{}) (wei weidata) { var dat map[string]interface{} dat = m1.(map[string]interface{}) wei = weidata{dat["uri"].(string),dat["user_name"].(string),dat["content"].(string),string(dat["Jokeid"].(json.Number))} fmt.Println("",wei) return } type weidata struct { url string title string content string key string } func main() { fmt.Println(`Get index ...`) _,statusCode := Get("http://lengxiaohua.com/lengxiaohuaapi/joke?action=getJokes&interval=weekly&sort=popular&type=text%7Cimage&start=0&limit=20") if statusCode != 200 { return } }运行结果:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |