当前位置:网站首页>Go language - JSON processing
Go language - JSON processing
2022-07-03 09:15:00 【Fill your head with water】
List of articles
□ JSON Handle
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 .
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/
1. code JSON ( marshalling | marshaling Marshaling)
1. Marhsal()
Encode data into json character string
// func Marshal(v interface{}) ([]byte, error){}
// Sample code :
// Test11 go json.Marshal when , The structure field needs to be capitalized otherwise Marshal Time does not show
type Test11 struct {
Name string
age string
}
func main() {
t1 := Test11{
"sb", "12"}
// Generate a paragraph JSON Formatted text
// If coding is successful , err Assign a value of zero nil, Variable b It will be a process JSON After formatting []byte type
b, err := json.Marshal(t1)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(b) // [123 34 78 97...]
fmt.Println(string(b)) // {"Name":"sb"}
}
}
2. MarshalIndent
Encode data into json character string for example map stuct etc.
// MarshalIndent It's like Marshal, Just format the output with indentation
func MarshalIndent(v interface{
}, prefix, indent string) ([]byte, error)
// v: Want to code into json The structure of the body |map
// prefix: Prefix , It is usually set to "" that will do .
// indent: Indent , Usually set to tab \t that will do
// Sample code :
func main() {
t1 := Test11{
"sb", 12}
b,_ := json.MarshalIndent(t1,"","\t")
fmt.Println(string(b))
// {
// "Name": "sb",
// "Age": 12
// }
}
MarshalIndent Compared with Marhsal() The difference between reading results and doing Indent To deal with :
Indent The code is a little long , Simply put, yes Json More format processing .
3. struct tag
We see that the first letter of the output field name above is capitalized , What if you want to use lowercase initials ? Change the field name of the structure to lowercase ?
JSON When outputting, you must pay attention to , Only exported fields ( The initial is capital ) Will be output , If you modify the field name , Then you will find that nothing will be output , So we have to go through struct tag Define to achieve .
in the light of JSON Output , We are defining struct tag There are a few points to pay attention to when :
Field tag yes "-", Then this field will not be output to JSON
tag With custom name in , Then the custom name will appear in JSON In the field name of
tag If there is "omitempty" Options , If the field value is empty , It will not be output to JSON In a string
If the field type is bool, string, int, int64 etc. , and tag With medium ",string" Options , Then this field is output to JSON The corresponding value of this field will be converted into JSON character string
The sample code :
type Test11 struct {
// 1. Field tag yes "-", Then this field will not be output to JSON
Name string `json:"-"`
// 2. Convert to string , Then the output
Age int `json:",string"` // --- "Age": "12",
// Age int `json:"Age"` // --- "Age": 12,
// 3. Subjects The value of will be evaluated twice JSON code
Sex string `json:"Sex"`
// 4. If Height It's empty , Is not output to JSON In a string Without this tag Will be displayed Height:""
Height string `json:"Height,omitempty"`
// 5. tag With custom name in , Then the custom name will appear in JSON In the field name of
Score int `json:" achievement "`
}
func main() {
t1 := Test11{
Name: "sb", Age:12,Sex:" male ",Score: 98}
b,_ := json.MarshalIndent(t1,"","\t")
fmt.Println(string(b))
}
4. adopt map Generate JSON
func main() {
m:= map[string]string{
"one":" Hello ","two":" I am a ","three":" Wang Wang team "}
v,err :=json.MarshalIndent(m,"","\t")
if err!=nil{
fmt.Println(err) // error message
}else{
fmt.Println(string(v))
}
// {
// "one": " Hello ",
// "three": " Wang Wang team ",
// "two": " I am a "
// }
}
2. decode JSON( Disaggregation | Unseal :Unmarshaling)
Json Unmarshal: take json The string is decoded to the corresponding data structure .
func Unmarshal(data []byte, v interface{
}) error
// data: to want to json Decoded []byte Type data
// v: take data Json Decode to v( It can be a structure |map) in
// The sample code
func main() {
t1 := Test11{
Name: "sb", Age:12,Sex:" male ",Score: 98}
val,_ := json.MarshalIndent(t1,"","\t")
fmt.Println(string(val)) // Last time json
// {
// "Age": "12",
// "Sex": " male ",
// " achievement ": 98
// }
var a interface{
}
err := json.Unmarshal(val,&a)
if err!=nil {
fmt.Println(err)
}
fmt.Println(a) // map[Age:12 Sex: male achievement :98]
fmt.Printf("%T\n",a) // map[string]interface {}
}
Unmarshal ( Demultiplexer ) analysis JSON Encode the data and store the results to v
In the value that points to .
If v
by nil
Or not a pointer ,Unmarshal return InvalidUnmarshalError
.
To put JSON Disaggregate into structure ,Unmarshal ( Disaggregation ) Match incoming objects Marshaling( marshalling ) Handle the keys used by the keys ( Structure field name or its tag ), Prefer precise matching , But it also accepts case insensitive matching .
By default , Object keys without corresponding structure fields are ignored ( That is to say, you have fields , I'll explain it to you ( Such as fields Age); Fields you don't have , Just ignore it ( Such as fields Sex); It has no fields , You are the default ( Such as fields S)).
and , The structure you gave ( For example, structure ) If the field has been assigned , No way Unmarshal ( Disaggregation ) To overwrite the original value .
for example :
type Test struct {
Name string `json:"Name"`
Age int `json:",string,age"`
S int `json:"S"`
}
func main() {
// The use of Json code val It's from the code above
// {
// "Age": "12",
// "Sex": " male ",
// " achievement ": 98
// }
var a Test
_ := json.Unmarshal(val,&a)
fmt.Printf("%#v\n",a) // main.Test{Name:"", Age:12, S:0}
var b Test = Test{
"12",12,2} // If it is resolved to b in
_ := json.Unmarshal(val,&b)
fmt.Printf("%#v\n",a) // main.Test{Name:"12", Age:12, S:2} You can see it Fields that have been assigned will not be overwritten .
}
To put JSON Unmarshal ( Disaggregation ) by interface value,Unmarshal ( Disaggregation ) Store one of them in the interface value :
bool—— be used for JSON Boolean value
float64—— be used for JSON Numbers
character string —— be used for JSON character string
[ ]interface{}—— be used for JSON Array
map[string]interface{}—— be used for JSON object ( Commonly used )
----> This is why it is resolved to an empty interface , What came out was map[string]interfacenil—— Express JSON null
Ungroup to slice Slice
To put JSON Array Unmarshal ( Disaggregation ) To slice , Ungroup sets the reset slice length to zero , Then attach each element to the slice .
As a special case , Empty JSON The array is ungrouped into slices , Unmarshalling will replace slices with new empty slices .
Ungroup to array Array
To put JSON Array Disaggregation by Go Array , Ungroup decoding JSON Array elements are converted to corresponding Go Array elements .
If Go Array is less than JSON Array , other JSON Array elements will be discarded .
If JSON Array is less than Go Array , Additional Go The array element is set to zero .
The solution group to map
To put JSON Objects are ungrouped to map in ,Unmarshal ( Disaggregation ) First established map Use .
If map by nil, be Unmarshal ( Disaggregation ) Assign a new map.
otherwise , Just Unmarshal ( Disaggregation ) Reuse existing map, Keep existing entries ( That is, save the value you have assigned now ).
then Unmarshal ( Disaggregation ) Storage slave JSON Object to map The key/value pair .
|
map The key type of must be any string type , It can also be int,implement json.Unmarshaler.Written in the source code : The map's key type must either be any string type, an integer, implement json.Unmarshaler, or implement encoding.TextUnmarshaler.
If JSON The value is not suitable for the given target type , perhaps , If JSON The number overflows the target type , Then ungroup (Marshal) Skip this field And try to complete Unmarshal ( Disaggregation ).
If you don't encounter more serious errors , be Unmarshal ( Disaggregation ) Return the... That describes the earliest such error Unmarshal ( Disaggregation ) Type error .
Null value disaggregation
JSON Null value Unmarshal ( Disaggregation ) by interface{}、map、 Pointer or slice by placing Go Value is set to nil.
because null stay JSON Is often used to express `not present ', take JSON null Ungroup to any other Go None of the types are valid on this value , There won't be any mistakes .
边栏推荐
- LeetCode 515. Find the maximum value in each tree row
- Pic16f648a-e/ss PIC16 8-bit microcontroller, 7KB (4kx14)
- 2022-2-13 learn the imitation Niuke project - Project debugging skills
- CSDN markdown editor help document
- The less successful implementation and lessons of RESNET
- 数字化管理中台+低代码,JNPF开启企业数字化转型的新引擎
- Binary tree sorting (C language, int type)
- What is an excellent fast development framework like?
- Method of intercepting string in shell
- 【点云处理之论文狂读前沿版9】—Advanced Feature Learning on Point Clouds using Multi-resolution Features and Learni
猜你喜欢
AcWing 787. 归并排序(模板)
LeetCode 515. Find the maximum value in each tree row
Character pyramid
【点云处理之论文狂读经典版13】—— Adaptive Graph Convolutional Neural Networks
Too many open files solution
2022-2-14 learning the imitation Niuke project - send email
精彩回顾|I/O Extended 2022 活动干货分享
Tree DP acwing 285 A dance without a boss
[point cloud processing paper crazy reading classic version 10] - pointcnn: revolution on x-transformed points
LeetCode 1089. Duplicate zero
随机推荐
【点云处理之论文狂读经典版7】—— Dynamic Edge-Conditioned Filters in Convolutional Neural Networks on Graphs
Facial expression recognition based on pytorch convolution -- graduation project
AcWing 785. 快速排序(模板)
Just graduate student reading thesis
数字化转型中,企业设备管理会出现什么问题?JNPF或将是“最优解”
[point cloud processing paper crazy reading frontier version 11] - unsupervised point cloud pre training via occlusion completion
We have a common name, XX Gong
2022-2-13 learn the imitation Niuke project - Project debugging skills
LeetCode 30. Concatenate substrings of all words
Character pyramid
LeetCode 532. K-diff number pairs in array
LeetCode 57. Insert interval
Introduction to the basic application and skills of QT
AcWing 788. 逆序对的数量
LeetCode 508. 出现次数最多的子树元素和
LeetCode 1089. Duplicate zero
What is the difference between sudo apt install and sudo apt -get install?
Low code momentum, this information management system development artifact, you deserve it!
Memory search acwing 901 skiing
Discussion on enterprise informatization construction