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

边栏推荐
- 【开发笔记】基于机智云4G转接板GC211的设备上云APP控制
- 項目經驗分享:實現一個昇思MindSpore 圖層 IR 融合優化 pass
- Some experiences of Arduino soft serial port communication
- 【LeetCode】3. Merge Two Sorted Lists·合并两个有序链表
- Understanding of class
- SQL create temporary table
- Jeecg data button permission settings
- Lucene introduces NFA
- Analysis of the ninth Blue Bridge Cup single chip microcomputer provincial competition
- An overview of IfM Engage
猜你喜欢

Leetcode 198: house raiding

技术干货|昇思MindSpore创新模型EPP-MVSNet-高精高效的三维重建
![[coppeliasim4.3] C calls UR5 in the remoteapi control scenario](/img/ca/2f72ea3590c358a6c9884aaa1a1c33.png)
[coppeliasim4.3] C calls UR5 in the remoteapi control scenario

c语言指针的概念

圖像識別與檢測--筆記

The concept of C language pointer

Project experience sharing: realize an IR Fusion optimization pass of Shengsi mindspire layer

论文学习——鄱阳湖星子站水位时间序列相似度研究

Technical dry goods | reproduce iccv2021 best paper swing transformer with Shengsi mindspire

Usage of requests module
随机推荐
Analysis of the problems of the 10th Blue Bridge Cup single chip microcomputer provincial competition
PdfWriter. GetInstance throws system Nullreferenceexception [en] pdfwriter GetInstance throws System. NullRef
技术干货|利用昇思MindSpore复现ICCV2021 Best Paper Swin Transformer
Unified handling and interception of exception exceptions of vertx
【LeetCode】2. Valid Parentheses·有效的括号
Vertx's responsive MySQL template
SQL create temporary table
Segment read
Download address collection of various versions of devaexpress
Partage de l'expérience du projet: mise en œuvre d'un pass optimisé pour la fusion IR de la couche mindstore
Grpc message sending of vertx
Vertx's responsive redis client
Lucene hnsw merge optimization
Various postures of CS without online line
Traversal in Lucene
Analysis of the ninth Blue Bridge Cup single chip microcomputer provincial competition
TypeScript let与var的区别
不出网上线CS的各种姿势
Some basic operations of reflection
An overview of IfM Engage