go web :5 用Interface{}简化对json的处理
来源:互联网 发布:美服lol汉化补丁mac 编辑:程序博客网 时间:2024/06/11 01:40
使用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
- go web :5 用Interface{}简化对json的处理
- go的json处理
- GO interface的使用
- 棒棒哒的Go Interface
- go语言JSON处理
- go interface 转 string,解析json
- go语言--爬虫--对字符串的处理
- 使用kvc机制简化对json的解析
- ios使用kvc机制简化对json的解析
- ajax对json的处理
- JSON对null的处理
- 浅解 go 语言的 interface
- Go 接口interface 的用法
- Go学习笔记:json处理
- GO语言学习:JSON处理
- Go语言之JSON处理
- web对mediaplayer的处理
- Go --- InterFace
- bzoj4985 评分(二分答案+dp)
- Your branch is ahead of 'origin/master' by 1 commit
- 4010: [HNOI2015]菜肴制作
- 业务层刻意抛出异常,全局异常的捕获它并按格式返回
- IntelliJ IDEA导入多个eclipse项目到同一个workspace下
- go web :5 用Interface{}简化对json的处理
- spring注解的使用
- pandas.read_csv参数整理
- Intellij IDEA 中文输入框不跟随怎么办?
- linux R-3.4.1实测源码编译安装
- 使用Docker部署Mysql时中文乱码问题
- 强力推荐!那些你不能错过的 GitHub 插件和工具
- xcode设置
- jQuery自定义方法之hover()