当前位置:网站首页>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 .
边栏推荐
- Jenkins learning (I) -- Jenkins installation
- 【点云处理之论文狂读经典版7】—— Dynamic Edge-Conditioned Filters in Convolutional Neural Networks on Graphs
- Binary tree traversal (first order traversal. Output results according to first order, middle order, and last order)
- AcWing 788. Number of pairs in reverse order
- Method of intercepting string in shell
- String splicing method in shell
- [point cloud processing paper crazy reading classic version 9] - pointwise revolutionary neural networks
- LeetCode 1089. Duplicate zero
- Instant messaging IM is the countercurrent of the progress of the times? See what jnpf says
- 【点云处理之论文狂读前沿版12】—— Adaptive Graph Convolution for Point Cloud Analysis
猜你喜欢

Pic16f648a-e/ss PIC16 8-bit microcontroller, 7KB (4kx14)

Character pyramid

CSDN markdown editor help document
[graduation season | advanced technology Er] another graduation season, I change my career as soon as I graduate, from animal science to programmer. Programmers have something to say in 10 years

一个优秀速开发框架是什么样的?

On February 14, 2022, learn the imitation Niuke project - develop the registration function

推荐一个 yyds 的低代码开源项目

LeetCode 75. Color classification

LeetCode 508. The most frequent subtree elements and

状态压缩DP AcWing 91. 最短Hamilton路径
随机推荐
Bert install no package metadata was found for the 'sacraments' distribution
On February 14, 2022, learn the imitation Niuke project - develop the registration function
LeetCode 1089. Duplicate zero
[point cloud processing paper crazy reading frontier edition 13] - gapnet: graph attention based point neural network for exploring local feature
[point cloud processing paper crazy reading classic version 11] - mining point cloud local structures by kernel correlation and graph pooling
[point cloud processing paper crazy reading classic version 10] - pointcnn: revolution on x-transformed points
【点云处理之论文狂读经典版9】—— Pointwise Convolutional Neural Networks
On a un nom en commun, maître XX.
LeetCode 57. 插入区间
Uc/os self-study from 0
MySQL installation and configuration (command line version)
The method of replacing the newline character '\n' of a file with a space in the shell
Vscode connect to remote server
干货!零售业智能化管理会遇到哪些问题?看懂这篇文章就够了
Computing level network notes
What is the difference between sudo apt install and sudo apt -get install?
教育信息化步入2.0,看看JNPF如何帮助教师减负,提高效率?
Education informatization has stepped into 2.0. How can jnpf help teachers reduce their burden and improve efficiency?
Method of intercepting string in shell
Sword finger offer II 029 Sorted circular linked list