golang学习之html json解析 - Go语言中文社区

golang学习之html json解析



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
	}

}
运行结果:



版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/liuwenhan999/article/details/44452981
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2019-08-25 15:30:27
  • 阅读 ( 1812 )
  • 分类:前端

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢