设为首页 加入收藏

TOP

Go处理json数据(四)
2018-12-07 02:05:57 】 浏览:500
Tags:处理 json 数据
else if err != nil { log.Fatal(err) } fmt.Printf("%s: %s\n", m.Name, m.Text) }

输出:

Ed: Knock knock.
Sam: Who's there?
Ed: Go fmt.
Sam: Go fmt who?
Ed: Go fmt yourself!

再例如,从标准输入读json数据,解码后删除名为Name的元素,最后重新编码后输出到标准输出。

func main() {
    dec := json.NewDecoder(os.Stdin)
    enc := json.NewEncoder(os.Stdout)
    for {
        var v map[string]interface{}
        if err := dec.Decode(&v); err != nil {
            log.Println(err)
            return
        }
        for k := range v {
            if k != "Name" {
                delete(v, k)
            }
        }
        if err := enc.Encode(&v); err != nil {
            log.Println(err)
        }
    }
}

json转Go数据结构工具推荐

quicktype工具,可以轻松地将json文件转换成各种语言对应的数据结构。

地址:https://quicktype.io

在vscode中有相关插件

  1. 先在命令面板中输入"set quicktype target language"选择要将json转换成什么语言的数据结构(比如Go)
  2. 再输入"open quicktype for json"就可以将当前json文件转换对应的数据结构(比如struct)

转换后只需按实际的需求稍微修改一部分类型即可。比如为json顶级匿名对象对应的struct设定名称,还有一些无法转换成struct时因为判断数据类型而使用的interface{}类型也要改一改。

例如,下面是使用quicktype工具对前面示例json数据进行转换后的数据结构:

type A struct {
    ID        int64         `json:"id"`       
    Content   string        `json:"content"`  
    Author    Author        `json:"author"`   
    Published bool          `json:"published"`
    Label     []interface{} `json:"label"`    
    NextPost  interface{}   `json:"nextPost"` 
    Comments  []Comment     `json:"comments"` 
}

type Author struct {
    ID   int64  `json:"id"`  
    Name string `json:"name"`
}

type Comment struct {
    ID      int64  `json:"id"`     
    Content string `json:"content"`
    Author  string `json:"author"` 
}

其中需要将type A struct的A改成你自己的名称,将A中的interface{}也改成合理的类型。

首页 上一页 1 2 3 4 下一页 尾页 4/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Go Web:RESTful web service示例 下一篇2018/12/05学习笔记

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目