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

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

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 = template.Must(tmpl.ParseFiles("template/index.html"))

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

前端:

<html>
    <head>
        <title>演示信息</title>
    </head>
    <body>
        {{index . "id"}}
        {{$imgs := index . "imgs"}}
        {{range $imgs}}
            {{index . "name"}}
        {{end}}
    </body>
</html>

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

{"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"}]}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值