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
	}

}
运行结果:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值