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

边栏推荐
- JS monitors empty objects and empty references
- Chapter VI - Containers
- URL programming
- 研究显示乳腺癌细胞更容易在患者睡觉时进入血液
- How long is the fastest time you can develop data API? One minute is enough for me
- Mail sending of vertx
- The babbage industrial policy forum
- PAT甲级 1030 Travel Plan
- Vertx multi vertical shared data
- Download address collection of various versions of devaexpress
猜你喜欢

【LeetCode】3. Merge Two Sorted Lists·合并两个有序链表

The embodiment of generics in inheritance and wildcards

Analysis of the eighth Blue Bridge Cup single chip microcomputer provincial competition

Reconnaissance et détection d'images - Notes

技术干货|关于AI Architecture未来的一些思考

PAT甲级 1032 Sharing

Leetcode 213: looting II

技术干货|昇思MindSpore NLP模型迁移之Bert模型—文本匹配任务(二):训练和评估

Go language foundation ----- 02 ----- basic data types and operators

Lucene hnsw merge optimization
随机推荐
Leetcode 198: 打家劫舍
Technical dry goods Shengsi mindspire elementary course online: from basic concepts to practical operation, 1 hour to start!
Lombok -- simplify code
UA camouflage, get and post in requests carry parameters to obtain JSON format content
Lucene merge document order
Jeecg menu path display problem
Project experience sharing: realize an IR Fusion optimization pass of Shengsi mindspire layer
Segment read
URL programming
你开发数据API最快多长时间?我1分钟就足够了
Sent by mqtt client server of vertx
【MySQL 13】安装MySQL后第一次修改密码,可以可跳过MySQL密码验证进行登录
技术干货|昇思MindSpore NLP模型迁移之Bert模型—文本匹配任务(二):训练和评估
项目经验分享:基于昇思MindSpore实现手写汉字识别
Implementation of breadth first in aggregation in ES
图像识别与检测--笔记
截图工具Snipaste
Why is data service the direction of the next generation data center?
技术干货|关于AI Architecture未来的一些思考
Lucene skip table