当前位置:网站首页>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)
}
}
}

边栏推荐
- Vertx restful style web router
- 不出网上线CS的各种姿势
- Understanding of class
- Technical dry goods Shengsi mindspire elementary course online: from basic concepts to practical operation, 1 hour to start!
- C WinForm framework
- Shengsi mindspire is upgraded again, the ultimate innovation of deep scientific computing
- Read config configuration file of vertx
- 技术干货|百行代码写BERT,昇思MindSpore能力大赏
- Spa single page application
- Technical dry goods Shengsi mindspire lite1.5 feature release, bringing a new end-to-end AI experience
猜你喜欢

Application of pigeon nest principle in Lucene minshouldmatchsumscorer

截图工具Snipaste

Lucene introduces NFA

技术干货|昇思MindSpore算子并行+异构并行,使能32卡训练2420亿参数模型

技术干货 | AlphaFold/ RoseTTAFold开源复现(2)—AlphaFold流程分析和训练构建

密西根大学张阳教授受聘中国上海交通大学客座教授(图)

Custom generic structure

Technical dry goods | hundred lines of code to write Bert, Shengsi mindspire ability reward

PAT甲级 1029 Median

技术干货|昇思MindSpore可变序列长度的动态Transformer已发布!
随机推荐
Common architectures of IO streams
技术干货|关于AI Architecture未来的一些思考
【MySQL 12】MySQL 8.0.18 重新初始化
Comparison of advantages and disadvantages between most complete SQL and NoSQL
Collector in ES (percentile / base)
研究显示乳腺癌细胞更容易在患者睡觉时进入血液
Circuit, packet and message exchange
UA camouflage, get and post in requests carry parameters to obtain JSON format content
PAT甲级 1029 Median
IndexSort
PdfWriter. GetInstance throws system Nullreferenceexception [en] pdfwriter GetInstance throws System. NullRef
Jeecg request URL signature
JS monitors empty objects and empty references
Lucene skip table
Read config configuration file of vertx
论文学习——鄱阳湖星子站水位时间序列相似度研究
Analysis of the problems of the 11th Blue Bridge Cup single chip microcomputer provincial competition
专题 | 同步 异步
Pgadmin 4 v6.11 release, PostgreSQL open source graphical management tool
PAT甲级 1032 Sharing