当前位置:网站首页>Go language foundation ------ 12 ------ JSON
Go language foundation ------ 12 ------ JSON
2022-07-03 07:37:00 【Mango sauce】
1 json Introduce
JSON (JavaScript Object Notation) It's a ratio. XML More lightweight data exchange format , While it is easy for people to read and write , It is also easy to parse and generate programs . Even though JSON yes JavaScript A subset of , but JSON Use text format completely independent of programming language , And behave as a key / A textual description of a set of value pairs ( Similar to the dictionary structure in some programming languages ), This makes it an ideal 、 Cross platform 、 Cross language data exchange language .
for example :
{
"company": "itcast",
"subjects": [
"Go",
"C++",
"Python",
"Test"
],
"isok": true,
"price": 666.666
}
Developers can use JSON Transfer simple strings 、 Numbers 、 Boolean value , You can also transfer an array , Or a more complex composite structure . stay Web In the field of development , JSON Widely used in Web Data communication between server program and client .
Go Language built-in pair JSON Support for . Use Go Language built in encoding/json Standard library , Developers can easily use Go Program generation and parsing JSON Formatted data .
JSON Official website :http://www.json.org/.
Online formatting :http://www.json.cn/.
2 Generate from structure json
package main
import (
"encoding/json"
"fmt"
)
// Member variable names must be capitalized
type IT struct {
Company string
Subjects []string
IsOk bool
Price float64
}
func main() {
// 1. Define a structure variable , Simultaneous initialization
s := IT{
"itcast", []string{
"Go", "C++", "Python", "Test"}, true, 666.666}
// 2. code , Build from content json Text
//buf, err := json.Marshal(s) // There is no corresponding line break
buf, err := json.MarshalIndent(s, "", " ")// Or use this format to generate , There will be corresponding line breaks
if err != nil {
fmt.Println("err = ", err)
return
}
fmt.Println("buf = ", string(buf))
}
3 struct_tag Use
We can see from the above example , We generate from the structure json Of key It's all in capitals , Because the structure name is in go Words that are not capitalized in language , Without access , This kind of problem will affect our understanding of json Of key Name , therefore go The official gave struct_tag Methods to modify the generation json when , Corresponding key Name .
package main
import (
"encoding/json"
"fmt"
)
// Member variable names must be capitalized
type IT struct {
//Company string `json:"-"` // This field will not be output to the screen
// '' After the single quotation mark is struct, Represents secondary code , You can generate json Of key From uppercase to lowercase
Company string `json:"company"`
Subjects []string `json:"subjects"`
IsOk bool `json:"isok"`
//IsOk bool `json:"string"`// Turn it into a string and then output the encoding
Price float64 `json:"price"`
}
func main() {
// 1. Define a structure variable , Simultaneous initialization
s := IT{
"itcast", []string{
"Go", "C++", "Python", "Test"}, true, 666.666}
// 2. code , Build from content json Text
buf, err := json.MarshalIndent(s, "", " ") // Format coding
if err != nil {
fmt.Println("err = ", err)
return
}
fmt.Println("buf = ", string(buf))
}
4 adopt map Generate json
package main
import (
"encoding/json"
"fmt"
)
func main() {
// 1. Create a map, Be careful value Is the universal pointer type
m := make(map[string]interface{
}, 4)
m["company"] = "itcast"
m["subjects"] = []string{
"Go", "C++", "Python", "Test"}
m["isok"] = true
m["price"] = 666.666
// 2. Code as json
//result, err := json.Marshal(m)
result, err := json.MarshalIndent(m, "", " ")
if err != nil {
fmt.Println("err = ", err)
return
}
fmt.Println("result = ", string(result))
}
5 json Resolve to structure
package main
import (
"encoding/json"
"fmt"
)
type IT struct {
Company string `json:"company"`
Subjects []string `json:"subjects"` // Secondary coding
IsOk bool `json:"isok"`
Price float64 `json:"price"`
}
func main() {
jsonBuf := ` { "company": "itcast", "subjects": [ "Go", "C++", "Python", "Test" ], "isok": true, "price": 666.666 }`
// One obtain json The whole thing
// 1. Define a structure variable
var tmp IT
// 2. The second parameter is address passing , Otherwise, the value of the variable cannot be modified
err := json.Unmarshal([]byte(jsonBuf), &tmp)
if err != nil {
fmt.Println("err = ", err)
return
}
//fmt.Println("tmp = ", tmp)
fmt.Printf("tmp = %+v\n", tmp)
// Two obtain json Specified content
type IT2 struct {
Subjects []string `json:"subjects"` // Secondary coding
}
var tmp2 IT2
err = json.Unmarshal([]byte(jsonBuf), &tmp2) // The second parameter is address passing
if err != nil {
fmt.Println("err = ", err)
return
}
fmt.Printf("tmp2 = %+v\n", tmp2)
}
6 json Resolved to map
package main
import (
"encoding/json"
"fmt"
)
func main() {
jsonBuf := ` { "company": "itcast", "subjects": [ "Go", "C++", "Python", "Test" ], "isok": true, "price": 666.666 }`
// 1. Create a map
m := make(map[string]interface{
}, 4)
// 2. The second parameter is address passing
err := json.Unmarshal([]byte(jsonBuf), &m)
if err != nil {
fmt.Println("err = ", err)
return
}
fmt.Printf("m = %+v\n", m)
//var str string
//str = string(m["company"])// err, Unable to convert ,
//str = m["company"].(string)// ok. Or get... Through type assertion map The content of .
//fmt.Printf("str = %s\n", str)
// 3. Types of assertions , value , It is value type
var str string
for key, value := range m {
//fmt.Printf("%v ============> %v\n", key, value)
switch data := value.(type) {
case string:
str = data
fmt.Printf("map[%s] The value type of is string, value = %s\n", key, str)
case bool:
fmt.Printf("map[%s] The value type of is bool, value = %v\n", key, data)
case float64:
fmt.Printf("map[%s] The value type of is float64, value = %f\n", key, data)
case []string:
fmt.Printf("map[%s] The value type of is []string, value = %v\n", key, data)
case []interface{
}:
fmt.Printf("map[%s] The value type of is []interface, value = %v\n", key, data)
}
}
}
边栏推荐
- Use of file class
- 技术干货|百行代码写BERT,昇思MindSpore能力大赏
- Technical dry goods | alphafold/ rosettafold open source reproduction (2) - alphafold process analysis and training Construction
- 项目经验分享:实现一个昇思MindSpore 图层 IR 融合优化 pass
- HCIA notes
- Logging log configuration of vertx
- Talk about floating
- 技术干货 | AlphaFold/ RoseTTAFold开源复现(2)—AlphaFold流程分析和训练构建
- TypeScript let与var的区别
- 技术干货|昇思MindSpore算子并行+异构并行,使能32卡训练2420亿参数模型
猜你喜欢
Reconnaissance et détection d'images - Notes
Traversal in Lucene
图像识别与检测--笔记
Go language foundation ----- 02 ----- basic data types and operators
Epoll related references
PdfWriter. GetInstance throws system Nullreferenceexception [en] pdfwriter GetInstance throws System. NullRef
项目经验分享:基于昇思MindSpore,使用DFCNN和CTC损失函数的声学模型实现
【MindSpore论文精讲】AAAI长尾问题中训练技巧的总结
密西根大学张阳教授受聘中国上海交通大学客座教授(图)
技术干货|昇思MindSpore可变序列长度的动态Transformer已发布!
随机推荐
Pgadmin 4 v6.11 release, PostgreSQL open source graphical management tool
技术干货|关于AI Architecture未来的一些思考
Map interface and method
Application of pigeon nest principle in Lucene minshouldmatchsumscorer
技术干货|昇思MindSpore创新模型EPP-MVSNet-高精高效的三维重建
Project experience sharing: realize an IR Fusion optimization pass of Shengsi mindspire layer
基于RNA的新型癌症疗法介绍
技术干货|AI框架动静态图统一的思考
Use of generics
技术干货|昇思MindSpore NLP模型迁移之Bert模型—文本匹配任务(二):训练和评估
Lombok -- simplify code
VMWare网络模式-桥接,Host-Only,NAT网络
The embodiment of generics in inheritance and wildcards
The concept of C language pointer
Responsive MySQL of vertx
List exercises after class
Dora (discover offer request recognition) process of obtaining IP address
SQL create temporary table
Project experience sharing: Based on mindspore, the acoustic model is realized by using dfcnn and CTC loss function
PAT甲级 1032 Sharing