HTML JSON parsing of Golang learning

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.


Golang Parsing HTML files

Because JSON is needed in the project, Https://github.com/bitly/go-simplejson.git is used

Download to the configuration of the &gopath path under SRC


The address of the connection is:

"Http://lengxiaohua.com/lengxiaohuaapi/joke?action=getJokes&interval=weekly&sort=popular&type=text %7cimage&start=0&limit=20 "

The steps are simple.

1. Connect URL to get page content

2. Convert page content to JSON

3. Parse JSON, print to console


The code is simple as follows, and it can be run directly

</pre><pre name= "code" class= "CPP" >//Testgocommand project Main.gopackage mainimport ("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 = -100return}defer resp. Body.close () data, err2: = Ioutil. ReadAll (resp. Body) if err2! = Nil {StatusCode = -200return}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. Statuscodecontent = return}/**interface coercion type conversion **/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 stringtitle stringcontent stringkey 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! = + (Return}}
Operation Result:



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.