Reference https://blog.go-zh.org/json-a...

Encoding

Encode的基本用法是

package mainimport ("encoding/json""fmt""os"
)type Message struct {Name stringBody stringTime int64
}func main() {message := Message{"Tom", "Hello", 1294706395881547000}b, err := json.Marshal(message)if err != nil {fmt.Fprintf(os.Stderr, "Failed to Marshal!")os.Exit(1)}fmt.Printf("%s", b)
}

输出为:

{"Name":"Tom","Body":"Hello","Time":1294706395881547000}
func Marshal(v interface{}) ([]byte, error)

Only data structures that can be represented as valid JSON will be encoded:

  • JSON objects only support string as keys.
  • Channel, complex, and function types cannot be encoded.
  • Cyclic data structures are not supported.
  • Pointers will be encoded as the values they point to(or null if the pointer is nil)

json package 只能access the exportede fields. 也就是首字母大写的field. 也就是在data structure中的首字母大写的field才会present in JSON output

Decoding

// We must first create a place where the decoded data will be stored
var output Message
// Please note that passing the pointer to output
decodeErr := json.Unmarshal(b, &output)
if decodeErr != nil {fmt.Fprintf(os.Stderr, "Failed to Unmarshal json data!err:%s", err)os.Exit(1)
}fmt.Printf("%+v\n", output)

Unmarshal是怎么确认json field与data structure的对应关系呢?,其实是通过以下来判断的(优先级从高到低).比如对于JSON Field "Foo"来说,

  • An exported field with a tag of "Foo".
  • An exported field named "Foo"
  • An exported field named "FOO" or "FoO" or some other case-insensitive match of "Foo"

总结下来是: Tag -> Foo -> FOO(case-insensitive match)
tag的判定规则如下

// Field appears in JSON as key "myName".
Field int `json:"myName"`// Field appears in JSON as key "myName" and
// the field is omitted from the object if its value is empty,
// as defined above.
Field int `json:"myName,omitempty"`// Field appears in JSON as key "Field" (the default), but
// the field is skipped if empty.
// Note the leading comma.
Field int `json:",omitempty"`// Field is ignored by this package.
Field int `json:"-"`// Field appears in JSON as key "-".
Field int `json:"-,"`

如果json data 与data structure中只有部分field匹配怎么办?

var unmatchedOutput UnmatchMessage
message1 :=
//` `代表原生字符串面值,没有转义操作,全是字符串的字面值
[]byte{`{"Name":"Tom","Body":"Hello","Time":1294706395881547000}`}
decodeErr1 := json.Unmarshal(b, &unmatchedOutput)
if decodeErr1 != nil {fmt.Fprintf(os.Stderr, "Failed to unmarshal json data! err:", err)os.Exit(1)
}
fmt.Printf("%+v\n", unmatchedOutput)

输出为

{Name:Tom Boy: Tim:0}

从上看出,Unmarshal只会decode符合上述3条件的field
This behavior is particularly useful when you wish to pick only a few specific fields out of a large JSON blob.

Generic JSON with interface{}

Decoding arbitrary data

以上2章先跳过去

Reference Types

Unmarshal会为Reference Types自动allocated a memory. 注意这里仅仅为在json 中存在的data allocate memory.

package mainimport ("encoding/json""fmt""os"
)type FamilyMember struct {Name    stringAge     intParents []string
}func main() {family := FamilyMember{"Andy", 26, []string{"Tom", "Lucy"}}b, err := json.Marshal(family)if err != nil {fmt.Fprintf(os.Stderr, "Failed to Marshal family!err:%s", err)os.Exit(1)}fmt.Printf("%s\n", b)// 注意,此时Parents slice是nil. 在Unmarshal时,会自动为其allcated memory.var output FamilyMemberdecodeErr := json.Unmarshal(b, &output)if decodeErr != nil {fmt.Fprintf(os.Stderr, "Failed to unmarshal!err:%s", err.Error())os.Exit(1)}fmt.Printf("%+v\n", output)
}

对于指针也是一样的

package mainimport ("encoding/json""fmt""os"
)type Bar int
type Foo struct {Bar *Bar
}func main() {b := []byte(`{"Bar":1234}`)var data Fooerr := json.Unmarshal(b, &data)if err != nil {fmt.Fprintf(os.Stderr, "Failed to unmarshal!err:%s", err.Error())os.Exit(1)}fmt.Printf("%+v\n", data)fmt.Printf("%+v\n", *(data.Bar))
}

输出为:

{Bar:0xc42001a120} // 注意此时的地址不为nil了,因为在Unmarshal已经为其allocated了memory
1234

但是需要注意,Unmarshal只会为json data匹配的field 分配内存,对于没有匹配的,可能还是nil. 所以对于如下的structure,在使用之前还需要认为的判断是否为nil.

type IncomingMessage struct {Cmd *CommandMsg *Message
}

Streaming Encoders and Decoders

package mainimport ("encoding/json""log""os"
)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 and Go相关推荐

  1. 【golang程序包推荐分享】分享亿点点golang json操作及myJsonMarshal程序包开发的踩坑经历 :)

    目录[阅读时间:约5分钟] 一.概述 1.Json的作用 2.Go官方 encoding/json 包 3. golang json的主要操作 二.Json Marshal:将数据编码成json字符串 ...

  2. Go 知识点(04)— 结构体字段转 json格式 tag 标签的作用

    我们知道在 Go 语言中无论是变量.常量还是函数,对于首字母大小写有不同的处理. 首字母大写,标志着该字段或者函数是能导出的,也就是可以被其它包所能访问的: 首字母小写,标志着该字段是私有的,只能在本 ...

  3. VS Code 配置调试参数、launch.json 配置文件属性、task.json 变量替换、自动保存并格式化、空格和制表符、函数调用关系、文件搜索和全局搜索、

    1. 生成配置参数 对于大多数的调试都需要在当前项目目录下创建一个 lanch.json 文件,位置是在当前项目目录下生成一个 .vscode 的隐藏文件夹,在里面放置一些配置内容,比如:settin ...

  4. Python 标准库之 json

    1. josn 定义 JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式.JSON的数据格式其实就是python里面的字典格式,里面可以包含 ...

  5. python中如何对复杂的json数据快速查找key对应的value值(使用JsonSearch包)

    前言 之前在实际的项目研发中,需要对一些复杂的json数据进行取值操作,由于json数据的层级很深,所以经常取值的代码会变成类似这样: value = data['store']['book'][0] ...

  6. 数据库里存json数据

    需求: 查询上个月每个人各个插件的总加分汇总为一个json存储到一个字段里 查询上个月每个组织机构插件的各个插件的总加分汇总为一个json存储到一个字段里 流程: 查询后返回结果是一个List集合,每 ...

  7. http传输json文件_python

    https://cloud.tencent.com/developer/article/1571365 http传输图片 https://www.cnblogs.com/jruing/p/122156 ...

  8. python:Json模块dumps、loads、dump、load介绍

    20210831 https://www.cnblogs.com/bigtreei/p/10466518.html json dump dumps 区别 python:Json模块dumps.load ...

  9. dataframe 转json

    20210810 字符串转换为字典的时候,如果没有引号会报找不到 这个名称 字符串类型变字典 本身含有字典的括号 列表里面本身要是字典类型 才能通过此方法 把列表转换为dataframe # 格式检查 ...

  10. Json文件解析(下

    Json文件解析(下) 代码地址:https://github.com/nlohmann/json 从STL容器转换 任何序列容器(std::array,std::vector,std::deque, ...

最新文章

  1. 解决机器学习问题的一般流程
  2. T-Mobile旗下网站又曝安全漏洞 允许任何人查看他人账户信息
  3. 秦九韶算法matlab程序,数值分析matlab程序实例.doc
  4. 复数卷积 tensorflow_PyTorch 中的傅里叶卷积
  5. 水彩在网页设计中应用的15个优秀案例
  6. java安装选择哪个可选功能_java章节习题及期末考试题答案.doc
  7. 什么是cmm3规范?什么是CMMI5 呢?
  8. 中国燕麦片市场销售现状与十四五发展趋势分析报告2022年版
  9. 论文必备:如何用卡片法写论文?
  10. PID控制器的输入量和输出量的物理关系解释
  11. 火车采集器采集内容页分页教程
  12. 清除 DNS 缓存( 附全平台详细教程 )
  13. 什么是SSH 以及常见的ssh 功能
  14. pytorch RuntimeError: size mismatch, m1: [64 x 784], m2: [784 x 10] at
  15. 【题目泛做】哲学题(DFS序)(Splay)
  16. 全新的MySQL 8.0行锁观测方式
  17. swiper插件实现轮播图
  18. 展望十二五:“核高基”突破核心技术走向产业化
  19. win11系统截图的几种方法
  20. 华为数通2022年10月 HCIP-Datacom-H12-821 第一章

热门文章

  1. Node的Web应用框架Express的简介与搭建HelloWorld
  2. 手把手教你Tomcat配置环境变量以及验证方法
  3. jenkins搭建流水线项目
  4. nacos如何搭建集群?nacos+nginx搭建集群,这一篇文章就够了!
  5. 【TensorFlow】笔记4:图像识别与CNN
  6. Re:CMM和RUP、XP的关系是什么?
  7. 春招不迷茫,模板刷题101实验室上线啦
  8. mac版lightroom cc_Photoshop问世30周年 Mac和iPad版获重要更新
  9. 神策数据招募优秀的解决方案销售和售前
  10. 如何帮助企业优化商业模式?看精益数据分析的“欺”与“破”