当前位置:网站首页>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)
}
}
}
边栏推荐
猜你喜欢
UA camouflage, get and post in requests carry parameters to obtain JSON format content
【LeetCode】3. Merge Two Sorted Lists·合并两个有序链表
Use of generics
Summary of Arduino serial functions related to print read
Comparison of advantages and disadvantages between most complete SQL and NoSQL
Various postures of CS without online line
PAT甲级 1030 Travel Plan
Understanding of class
[set theory] Stirling subset number (Stirling subset number concept | ball model | Stirling subset number recurrence formula | binary relationship refinement relationship of division)
Spa single page application
随机推荐
Vertx multi vertical shared data
Technology dry goods | luxe model for the migration of mindspore NLP model -- reading comprehension task
FileInputStream and fileoutputstream
Use of other streams
Understanding of class
Implementation of breadth first in aggregation in ES
【MySQL 11】怎么解决MySQL 8.0.18 大小写敏感问题
SQL create temporary table
The babbage industrial policy forum
Technical dry goods | hundred lines of code to write Bert, Shengsi mindspire ability reward
项目经验分享:基于昇思MindSpore,使用DFCNN和CTC损失函数的声学模型实现
URL programming
Lucene merge document order
An overview of IfM Engage
The babbage industrial policy forum
Technical dry goods Shengsi mindspire elementary course online: from basic concepts to practical operation, 1 hour to start!
Analysis of the ninth Blue Bridge Cup single chip microcomputer provincial competition
圖像識別與檢測--筆記
Industrial resilience
Technical dry goods | alphafold/ rosettafold open source reproduction (2) - alphafold process analysis and training Construction