登录
首页 >  Golang >  Go问答

go如何将两个切片转化为一段json?

来源:SegmentFault

时间:2023-02-24 14:08:48 274浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《go如何将两个切片转化为一段json?》,介绍一下goquery、Gin,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

问题描述

初学go,制作可以爬取百度热搜的爬虫,但是最终得到两个切片,不知道怎么弄成json,搜索发现网上资源太少了。
用了goquery和gin两个库。
理想效果是访问http://【ip】/api/v1/baidu/hot返回:

[
    {
        "title": "...",
        "img": "https://..."
    },
    {
        "title": "...",
        "img": "https://..."
    }
    // .......
]

相关代码

package main

import (
    "net/http"
    "strings"

    "github.com/PuerkitoBio/goquery"
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()
    // api
    api := r.Group("/api/v1")
    {
        baidu := api.Group("/baidu")
        {
            baidu.GET("/hot", getBaiduHotList)
        }
        api.GET("/", apiTest)
    }

    // 端口
    r.Run(":80")
}
func apiTest(c *gin.Context) {
    c.JSON(200, gin.H{
        "msg": "200",
    })
}
var (
    img   []string
    title []string
)

func getBaiduHotList(c *gin.Context) {
    resp, err := http.Get("https://top.baidu.com/board")
    if err != nil {
        panic(err)
    }

    dom, err := goquery.NewDocumentFromReader(resp.Body)
    if err != nil {
        panic(err)
    }
    dom.Find(".theme-hot .active-item_1Em2h .c-single-text-ellipsis").Each(
        func(i int, s *goquery.Selection) {
            title := append(title, strings.Join(strings.Fields(s.Text()), ""))
            // 然后就不知道怎么搞了
        })
    dom.Find(".theme-hot .active-item-img_3i_Tx").Each(
        func(i int, s *goquery.Selection) {
            src, _ := s.Attr("src")
            img := append(img, strings.Join(strings.Fields(src), ""))
            // 然后就不知道怎么搞了
        })

}

望大佬们指导一下,非常感谢。

正确答案

只是抓包的话,不需要用gin库,转json的话需要用json库

package main

import (
    "encoding/json"
    "fmt"
    "github.com/PuerkitoBio/goquery"
    "net/http"
)

type News struct {
    Img   string `json:"img"`
    Title string `json:"title"`
}

func main() {
    getBaiduHotList()
}

func getBaiduHotList() {
    var newsList []News
    resp, err := http.Get("https://top.baidu.com/board")
    if err != nil {
        panic(err)
    }
    dom, err := goquery.NewDocumentFromReader(resp.Body)
    if err != nil {
        panic(err)
    }
    dom.Find(".theme-hot .active-item_1Em2h").Each(
        func(i int, s *goquery.Selection) {
            img, _ := s.Find(".active-item-img_3i_Tx").Attr("src")
            title := s.Find(".c-single-text-ellipsis").Text()
            newsList = append(newsList, News{
                Img:   img,
                Title: title,
            })
        })
    res, err := json.Marshal(newsList)
    if err != nil {
        fmt.Println("格式化错误")
        fmt.Println(err.Error())
        return
    }
    fmt.Print(string(res))
}

调用方法

go run main.go

抓取结果

[{"img":"https://fyb-1.cdn.bcebos.com/hotboard_img/0341875b3e51ae15b2795c5714a4296f?x-bce-process=image/resize,m_fill,w_732,h_272","title":"  国家公路网将覆盖10万人以上市县 "},{"img":"https://fyb-1.cdn.bcebos.com/hotboard_img/d03ec9b7b50ff24500f990a5edc969a7?x-bce-process=image/resize,m_fill,w_732,h_272","title":"  警方将彻查被拖拽女生与男子关系 "},{"img":"https://fyb-1.cdn.bcebos.com/hotboard_img/8fcb8e1f492d161dd595cd88a0860e9e?x-bce-process=image/resize,m_fill,w_732,h_272","title":"  必胜客两家涉事门店被立案调查 "},{"img":"https://fyb-1.cdn.bcebos.com/hotboard_img/2d33a233bcdfb6b412a032524d038e65?x-bce-process=image/resize,m_fill,w_732,h_272","title":"  做好防汛关键期水旱灾害防御 "},{"img":"https://fyb-1.cdn.bcebos.com/hotboard_img/47a1e7d28270ab8322746e5171135325?x-bce-process=image/resize,m_fill,w_732,h_272","title":"  台媒:山东舰疑被美空军侦察机锁定 "},{"img":"https://fyb-1.cdn.bcebos.com/hotboard_img/f94c30082e448b0ae863a8c253547d76?x-bce-process=image/resize,m_fill,w_732,h_272","title":"  多人打砸烧烤摊:不打折就砸 "},{"img":"https://fyb-1.cdn.bcebos.com/hotboard_img/b68e4e6f4a3ab5869e8f06a56f07b5ec?x-bce-process=image/resize,m_fill,w_732,h_272","title":"  新冠康复者求职现状 "},{"img":"https://fyb-1.cdn.bcebos.com/hotboard_img/f6f5c5d516e67ecf030b1afd3e5a224e?x-bce-process=image/resize,m_fill,w_732,h_272","title":"  天津一居民楼燃爆 1死12伤3失联 "},{"img":"https://fyb-1.cdn.bcebos.com/hotboard_img/fdf013459bf6d8fbf560c5b7b064c0b3?x-bce-process=image/resize,m_fill,w_732,h_272","title":"  广西北海隔离环境不忍直视 "},{"img":"https://fyb-1.cdn.bcebos.com/hotboard_img/24eb04e273d1ba4795272e232b0b53e8?x-bce-process=image/resize,m_fill,w_732,h_272","title":"  女子发订婚宴照被谣传为会所技师 "},{"img":"https://fyb-1.cdn.bcebos.com/hotboard_img/d2f717b05338eb149e9d8c9839bbb9f7?x-bce-process=image/resize,m_fill,w_732,h_272","title":"  担心疫情被封外地 男子提前过年 "}]

注意转Json时结构体中变量首字母大写才可以导出

本篇关于《go如何将两个切片转化为一段json?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:SegmentFault 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>