当前位置:网站首页>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 .
边栏推荐
- 推荐一个 yyds 的低代码开源项目
- AcWing 785. 快速排序(模板)
- LeetCode 324. 摆动排序 II
- Simple use of MATLAB
- State compression DP acwing 91 Shortest Hamilton path
- STM32F103 can learning record
- [point cloud processing paper crazy reading classic version 9] - pointwise revolutionary neural networks
- LeetCode 515. 在每个树行中找最大值
- 我们有个共同的名字,XX工
- Methods of using arrays as function parameters in shell
猜你喜欢

教育信息化步入2.0,看看JNPF如何帮助教师减负,提高效率?
![[point cloud processing paper crazy reading classic version 7] - dynamic edge conditioned filters in revolutionary neural networks on Graphs](/img/0a/480f1d1eea6f2ecf84fd5aa96bd9fb.png)
[point cloud processing paper crazy reading classic version 7] - dynamic edge conditioned filters in revolutionary neural networks on Graphs

数位统计DP AcWing 338. 计数问题
![[point cloud processing paper crazy reading classic version 10] - pointcnn: revolution on x-transformed points](/img/c1/045ca010b212376dc3e5532d25c654.png)
[point cloud processing paper crazy reading classic version 10] - pointcnn: revolution on x-transformed points

【点云处理之论文狂读前沿版10】—— MVTN: Multi-View Transformation Network for 3D Shape Recognition

What are the stages of traditional enterprise digital transformation?

AcWing 788. Number of pairs in reverse order

【点云处理之论文狂读经典版10】—— PointCNN: Convolution On X-Transformed Points

传统办公模式的“助推器”,搭建OA办公系统,原来就这么简单!

Just graduate student reading thesis
随机推荐
[point cloud processing paper crazy reading frontier version 11] - unsupervised point cloud pre training via occlusion completion
AcWing 786. 第k个数
求组合数 AcWing 885. 求组合数 I
Using DLV to analyze the high CPU consumption of golang process
Debug debugging - Visual Studio 2022
2022-1-6 Niuke net brush sword finger offer
Discussion on enterprise informatization construction
MySQL installation and configuration (command line version)
Divide candy (circular queue)
Use the interface colmap interface of openmvs to generate the pose file required by openmvs mvs
Basic knowledge of network security
The "booster" of traditional office mode, Building OA office system, was so simple!
Shell script kills the process according to the port number
【点云处理之论文狂读前沿版8】—— Pointview-GCN: 3D Shape Classification With Multi-View Point Clouds
【点云处理之论文狂读前沿版13】—— GAPNet: Graph Attention based Point Neural Network for Exploiting Local Feature
[point cloud processing paper crazy reading classic version 9] - pointwise revolutionary neural networks
Binary tree sorting (C language, int type)
LeetCode 871. 最低加油次数
Complex character + number pyramid
Low code momentum, this information management system development artifact, you deserve it!