使用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"}]}