Home >Backend Development >Golang >How to extract JSON data from HTML using goquery in Golang?
Methods to use goquery to extract JSON data from HTML in Go are: Install goquery library: go get -u github.com/PuerkitoBio/goquery Load HTML document: goquery.NewDocument(htmlURL) Select elements containing JSON data: doc .Find(selector) gets JSON data: jsonDataElement.Text()
How to use goquery to extract JSON data from HTML in Golang?
Goquery is a Go library that allows you to parse, manipulate, and query HTML in a jQuery-like manner. It is useful for extracting JSON data from HTML.
Installation goquery
go get -u github.com/PuerkitoBio/goquery
Practical case
Let us consider a practical case of extracting JSON data from an HTML page. Suppose we have a page that contains the following JSON data:
<div id="json-data"> { "name": "John Doe", "age": 30, "city": "New York" } </div>
Using goquery, we can easily extract this JSON data:
package main import ( "fmt" "log" "github.com/PuerkitoBio/goquery" ) func main() { // 加载 HTML 文档 doc, err := goquery.NewDocument("https://example.com/page.html") if err != nil { log.Fatal(err) } // 从 HTML 中选择包含 JSON 数据的元素 jsonDataElement := doc.Find("#json-data") // 获取 JSON 数据 jsonData := jsonDataElement.Text() // 打印 JSON 数据 fmt.Println(jsonData) }
Output:
{ "name": "John Doe", "age": 30, "city": "New York" }
Conclusion
Extracting JSON data from HTML using goquery is very simple. Just load the HTML document, select the element containing the JSON data, and get the data. This is useful for automating tasks and extracting data from the network.
The above is the detailed content of How to extract JSON data from HTML using goquery in Golang?. For more information, please follow other related articles on the PHP Chinese website!