前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >go web :5 用Interface{}简化对json的处理

go web :5 用Interface{}简化对json的处理

作者头像
超级大猪
发布2019-11-22 09:37:53
5670
发布2019-11-22 09:37:53
举报
文章被收录于专栏:大猪的笔记大猪的笔记

使用go处理json,需要把它unmarshal到一个结构体。对于用惯了python的我,简直要吐血啊。 为了屏蔽掉讨厌的结构体,在处理json的时候,可以使用interface{}。具体姿势如下: 服务端:

代码语言:javascript
复制
func TestTemplate(w http.ResponseWriter, r *http.Request) {
    timeout := time.Duration(5 * time.Second)
    client := http.Client{
        Timeout: timeout,
    }
    resp, _ := client.Get("http://www.qiushibaike.com/img/restful/img?id=9166")
    str, _ := ioutil.ReadAll(resp.Body)

    var jsonObj interface{}
    err := json.Unmarshal(str, &jsonObj)
    if err != nil {
        panic("NewMyJson err" + err.Error())
    }

    tmpl := template.New("t1")
    tmpl = tmpl.Funcs(template.FuncMap{"toArr": ToArr,
        "toInt": ToInt,
        "toStr": ToStr,
        "toMap": ToMap,
        "get":   Get})
    tmpl = template.Must(tmpl.ParseFiles("template/index.html"))

    tmpl.ExecuteTemplate(w, "index.html", jsonObj)
}

前端:

代码语言:javascript
复制
<html>
    <head>
        <title>演示信息</title>
    </head>
    <body>
        {{index . "id"}}
        {{$imgs := index . "imgs"}}
        {{range $imgs}}
            {{index . "name"}}
        {{end}}
    </body>
</html>

顺带一说,json对象长这样:

代码语言:javascript
复制
{"id":9166,"name":"\u8ba9\u4f17\u7537\u4eba\u6d41\u9f3b\u8840\u7684\u6027\u611f\u5199\u771f\u56fe\u7247","url":"http:\/\/www.mm131.com\/qingchun\/594.html","type":0,"status":"normal","description":"","created_time":"2017-08-23 13:43:38","imgs":[{"id":51892,"aid":9166,"name":"059a05beb808569d8cdceb337f80cea8","img_type":"jpeg","status":"checked","size":"533*800"},{"id":51894,"aid":9166,"name":"c5b4bc5786a324b6aa99f4f4ed37046e","img_type":"jpeg","status":"checked","size":"533*800"},{"id":51895,"aid":9166,"name":"f3c1b82dbdd96b556366322f4adbcd27","img_type":"jpeg","status":"checked","size":"533*800"},{"id":51896,"aid":9166,"name":"4dbc208cce64ecac408737255959efd1","img_type":"jpeg","status":"checked","size":"533*800"},{"id":51897,"aid":9166,"name":"30f32f7be179c0d3eda756eac280bc3b","img_type":"jpeg","status":"checked","size":"533*800"},{"id":51899,"aid":9166,"name":"ad3875c231ba94b2c0e3f1fa9768e006","img_type":"jpeg","status":"checked","size":"533*800"},{"id":51900,"aid":9166,"name":"728998851a7fa7e47d6a492c1e721d7f","img_type":"jpeg","status":"checked","size":"533*800"},{"id":51901,"aid":9166,"name":"5353a12eb2887c0ebcf08c7bef71bff1","img_type":"jpeg","status":"checked","size":"533*800"},{"id":51903,"aid":9166,"name":"4a76d3d6f2e25f4a2651b07b50dbd8a7","img_type":"jpeg","status":"checked","size":"533*800"}]}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-09-08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档